我正在使用winston和node&快递和找不到一个合适的方法来简单地使用express的session.id扩充所有日志条目(通过广泛的谷歌和搜索搜索) - 任何建议?
答案 0 :(得分:0)
对于Express请求日志,您可以执行以下操作:
var morgan = require('morgan'),
winston = require('winston');
// Define a new format token
morgan.token('id', function(req, res) {
return req.session ? req.session.id : 'N/A';
});
// Create a stream using Winston for logging
var winstonStream = {
write: function(msg, encoding) {
winston.info(msg);
}
};
// Create a logger middleware that uses the new token in format
// and writes to Winston logging stream
var expressLogger = morgan(morgan.combined + ' - :id', { stream: winstonStream });
app.use(expressLogger);
不知道如何为每个winston[level]()
调用实现相同的操作,因为您需要手头有请求对象(除了将对象传递给每一位代码)。
答案 1 :(得分:0)
感谢您的回答,我需要稍微更广泛一点 - 即。无论我在哪里打电话给温斯顿,不仅仅是摩根请求记录。我已经覆盖了winston.log,所以我可以调用log.info(req,message)或log.warn等,会话ID从req传递给元信息。我也使用cookie会话,它不会为我创建会话ID,所以我的解决方案是:
var CustomLogger = function(options){
CustomLogger.super_.apply(this, arguments);
}
util.inherits(CustomLogger, winston.Logger);
CustomLogger.prototype.log = function () {
var args = Array.prototype.slice.call(arguments);
var req = args[1];
if (req.session) {
req.session.id = req.session.id || uuid.v4();
var meta = _.merge((args[3] || {}), {sessionId: req.session.id});
CustomLogger.super_.prototype.log.call(this, args[0], args[2] + ' | ', meta);
}
else {
// no req.session, assume req hasnt been passed in as 1st param
CustomLogger.super_.prototype.log.apply(this, arguments);
}
}
var logger = new CustomLogger({
transports: [ ... ],
exitOnError: false
});