Created
April 17, 2015 02:25
-
-
Save teamrun/2a456f1220d529981485 to your computer and use it in GitHub Desktop.
Stream output customize for bunyan
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * 格式化输出bunyan的log | |
| * bunyan默认输出 对象, 需要-g的bunyan cli来管道处理输出 | |
| * 这里配置stream为自己定制的stream, 拿到输出后进行解析 和 自定义 | |
| * | |
| * */ | |
| var path = require('path'); | |
| var Stream = require('stream'); | |
| var colors = require('colors'); | |
| var Moment = require('moment'); | |
| var stream = new Stream() | |
| stream.writable = true; | |
| // 各个level对应的颜色和名字 | |
| // bunyan输出的是数字代码 | |
| var colorSet = { | |
| 60: { | |
| color: 'underline.red', | |
| name: 'FATAL' | |
| }, | |
| 50: { | |
| color: 'red', | |
| name: 'ERROR' | |
| }, | |
| 40: { | |
| color: 'yellow', | |
| name: 'WARN ' | |
| }, | |
| 30: { | |
| color: 'blue', | |
| name: 'INFO ' | |
| }, | |
| 20: { | |
| color: 'green', | |
| name: 'DEBUG' | |
| }, | |
| 10: { | |
| color: 'grey', | |
| name: 'TRACE' | |
| } | |
| }; | |
| // bunyan输出的对象中原有的所有属性 | |
| var selfProps = ['hostname', 'name', 'pid', 'level', 'msg', 'time', 'src', 'v']; | |
| var basePath = g_config.base_path; | |
| function isEmptyObj(obj){ | |
| for(var i in obj){ | |
| return false; | |
| } | |
| return true; | |
| } | |
| stream.write = function(objStr) { | |
| // pretty-printing your message | |
| var obj = JSON.parse(objStr); | |
| var info = ''; | |
| var output; | |
| var color = colorSet[obj.level].color; | |
| var levelName = colorSet[obj.level].name; | |
| // 当地时间 | |
| var time = obj.time; | |
| info += Moment(time).format('YYYY-MM-DD HH:MM:SS'); | |
| info += ' '; | |
| info += levelName; | |
| info += ' '; | |
| // 从基础路径算起 | |
| var file = './' + path.relative(basePath, obj.src.file); | |
| var lineNumber = obj.src.line; | |
| info += file +':'+ lineNumber; | |
| info += ' '; | |
| info += obj.msg; | |
| // 如果第一个参数不是error,而是其他的对象, 则会将对象解构 | |
| var firstArgNotErr = {}; | |
| for(var i in obj){ | |
| if(selfProps.indexOf(i) < 0 && i !== 'err'){ | |
| firstArgNotErr[i] = obj[i]; | |
| } | |
| } | |
| if(!isEmptyObj(firstArgNotErr)){ | |
| info += '\n '+JSON.stringify(firstArgNotErr); | |
| } | |
| // 着色 | |
| output = info; | |
| color.split('.').forEach(function(c){ | |
| output = output[c]; | |
| }); | |
| // 如果log里有个是error: | |
| // 最后将error和stack输出 | |
| if(obj.err){ | |
| // output += '\n'+obj.err.stack; | |
| obj.err.stack.split('\n').forEach(function(line){ | |
| output += '\n '+line.magenta; | |
| }); | |
| } | |
| // console.log(obj) | |
| // console.log('------------------------------------\n') | |
| console.log(output); | |
| } | |
| module.exports = stream; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to use: