【发布时间】:2015-07-14 10:57:58
【问题描述】:
我一直在查看 bunyan 以登录我的 nodejs 应用程序。我试过了,一切似乎都很好。我在log.child 上跳过了a section,但现在我正在尝试了解如何使用它。我认为它的目的是允许我为日志条目指定一些特殊标识符,以便我可以唯一地识别该日志如何与其他日志条目相关联。
如果是这样,我会设想自己在每个请求中使用log.child:
var bunyan = require('bunyan');
var log = bunyan.createLogger({name: 'myapp'});
router.post('/submit', function(req, res) {
var logChild = log.child({reqId: uuid.v4()});
logChild.info({ req:req }, req.user.name + ' has called /submit');
saveData(req)
.then(function(data) {
logChild.info({data: data}, req.user.name + ' has saved to DB successfully in /submit');
res.json({'success': 'Saved!'});
})
.error(function(err) {
logChild.error({ err: err }, req.user.name + ' has caused an error in /submit ');
res.status(500).json("error": err});
});
});
这样,如果用户 Bob 在 30 秒内两次 POST 到 /submit,则日志文件中会有一些上下文区分两个不同的调用。
也就是说,我会看到这样的东西(带有上下文):
Bob has called /submit uuid: 109156be-c4fb-41ea-b1b4-efe1671c5836
Bob has called /submit uuid: 49dlsd7i-dapd-fdio-fei0-sd59fd0ph34d
Bob has saved to DB successfully in /submit uuid: 109156be-c4fb-41ea-b1b4-efe1671c5836
Bob has caused an error in /submit uuid: 49dlsd7i-dapd-fdio-fei0-sd59fd0ph34d
代替这个(没有上下文):
Bob has called /submit
Bob has called /submit
Bob has saved to DB successfully in /submit
Bob has caused an error in /submit
因此,对于我的 Nodejs 应用程序中的所有路由,我将创建 logChild 对象,然后使用 logChild 记录该路由中的条目。
我是否正确理解和实施log.child的用例?
【问题讨论】:
标签: javascript node.js logging express bunyan