![03ba832154faf26000a68ef86b841539.png](https://img-blog.csdnimg.cn/img_convert/03ba832154faf26000a68ef86b841539.png)
Bunyan是一个简单易用的JS日志框架,可以工作在多种环境下,这里以Nodejs为例说明Bunyan的基本用法。是时候替换console.log的写法了。
安装
npm install --save bunyan
使用
// hi.jsvar bunyan = require('bunyan');var log = bunyan.createLogger({name: 'myapp'});log.info('hi');log.warn({lang: 'fr'}, 'au revoir');
运行
node hi
默认输出json格式,对人类不友好。
![628e0d0bbd2744a0d84cac1ea7cf09af.png](https://img-blog.csdnimg.cn/img_convert/628e0d0bbd2744a0d84cac1ea7cf09af.png)
换一种运行方式
node hi.js | .ode_modules.binbunyan
![cefe96b7150f013597cdeb3800a6ebaa.png](https://img-blog.csdnimg.cn/img_convert/cefe96b7150f013597cdeb3800a6ebaa.png)
这样就有了易读的格式。
安装到全局:
npm install -g bunyan
指定log等级
node hi.js | bunyan -l warn
![2a79807c54f23d3712761b2381bf7eea.png](https://img-blog.csdnimg.cn/img_convert/2a79807c54f23d3712761b2381bf7eea.png)
指定多个输出
var bunyan = require('bunyan');//var log = bunyan.createLogger({name: 'myapp'});var log = bunyan.createLogger({ name: 'myapp', streams: [ { level: 'info', stream: process.stdout // log INFO and above to stdout }, { level: 'error', path: 'c:/temp/log/myapp-error.log' // log ERROR and above to a file } ]});log.info('hi');log.warn({lang: 'fr'}, 'au revoir');log.error('this is an error!');
将info及以上的log输出到控制台,将error及以上等级的log输出到文件。
![2dea1dc8c9d727476861f22f68659d65.png](https://img-blog.csdnimg.cn/img_convert/2dea1dc8c9d727476861f22f68659d65.png)
控制台输出
![3092ea20787ca8cac517d8d078a85170.png](https://img-blog.csdnimg.cn/img_convert/3092ea20787ca8cac517d8d078a85170.png)
文件输出
子日志log.child
bunyan可以客制化一个针对你的应用的子组件的日志
//hi.jsvar bunyan = require('bunyan');var log = bunyan.createLogger({name: 'myapp'});function Wuzzle(options) { this.log = options.log.child({widget_type: 'wuzzle'}); this.log.info('creating a wuzzle')}Wuzzle.prototype.woos = function () { this.log.warn('This wuzzle is woosey.')}log.info('start');var wuzzle = new Wuzzle({log: log});wuzzle.woos();log.info('done');
在Wuzzle中创建一个子日志,可以任意添加额外的信息(widget_type: 'wuzzle'),
![ae5267457c279abc512dfacbe3a4581d.png](https://img-blog.csdnimg.cn/img_convert/ae5267457c279abc512dfacbe3a4581d.png)
对象序列化
//hi.jsvar bunyan = require('bunyan');var http = require("http");function reqSerializer(req) { return{ method:req.method, url: req.url, headers: req.headers }}var log = bunyan.createLogger({name:'myapp',serializers:{req: reqSerializer}});http.createServer(function(req, res) {log.info({req:req});res.writeHead(200, {"Content-Type": "text/html"}); res.end(` HTML Response
Hi
`);}).listen(3000);log.info("File server running on port 3000");
![4a4ef8b04221a2b10ccce8fa61add2e0.png](https://img-blog.csdnimg.cn/img_convert/4a4ef8b04221a2b10ccce8fa61add2e0.png)
代码客制化request对象的输出日志,会输出请求方法,请求url和cookie信息。
运行
node hi.js | bunyan
运行后在浏览器浏览:
http://localhost:3000/
![4030d5be8a344fe047d1c8bcfde7e84c.png](https://img-blog.csdnimg.cn/img_convert/4030d5be8a344fe047d1c8bcfde7e84c.png)