Skip to content

Instantly share code, notes, and snippets.

@teamrun
Created April 17, 2015 02:25
Show Gist options
  • Select an option

  • Save teamrun/2a456f1220d529981485 to your computer and use it in GitHub Desktop.

Select an option

Save teamrun/2a456f1220d529981485 to your computer and use it in GitHub Desktop.
Stream output customize for bunyan
/*
* 格式化输出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;
@teamrun
Copy link
Copy Markdown
Author

teamrun commented Apr 17, 2015

how to use:

var logOptions = {
    stream:  outputStream
};
var opt = _.extend({}, g_config.logOpt, logOptions );
var log = bunyan.createLogger(opt);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment