使用Express.js

时间:2015-09-22 21:59:13

标签: node.js logging express trace winston

我需要生成带有跟踪ID的日志。目前我们正在使用winston进行日志记录

我正在使用winston容器,如下所示

var fs = require('fs');
var os = require('os');
var path = require('path');
var winston = require('winston');
var transports = [];

module.exports = function(setting) {

  function formatter(options) {
    return options.timestamp() +' '+ options.level.toUpperCase() +' '+ (undefined !== options.message ? options.message : '');
  }

  if (setting.log.file) {
    fs.existsSync(setting.log.path) || fs.mkdirSync(setting.log.path);
    transports.push(new winston.transports.DailyRotateFile({
      handleExceptions: true,
      json: true,
      component: setting.customise.app_type,
      datePattern: setting.log.datePattern,
      filename: path.join(setting.log.path, setting.log.filename),
      level: setting.log.level
    }));
  }
  if (setting.log.console || transports.length === 0) {
    transports.push(new (winston.transports.Console)({
      timestamp: function() {
        return new Date().toISOString();
      },
      handleExceptions: true,
      json: false,
      formatter: formatter,
      level: setting.log.level,
      colorize: 'all'
    }));
  }

  winston.loggers.add('defaultLogger', {
    transports: transports
  });

  var logger = winston.loggers.get('defaultLogger');
  logger.exitOnError = false;
  logger.addFilter(function(msg, meta, level) {
    if(!meta){
      meta = {};
    }
    meta.component= setting.customise.app_type;
    meta.component_version = setting.app_version;
    meta.machine = os.hostname();
    meta.context = process.pid;
    return msg;
  });
};

因此,在需要进行日志记录的文件中,只需执行

即可
var sessionTool = require('sessionTool')(app);

var logger = require('winston').loggers.get('defaultLogger');

快递使用winston

var winstonStream = {
      write: function(message, encoding){
          logger.info(message.slice(0, -1));
      }
  };
  app.use(express.logger({
      stream: winstonStream,
      format: ':remote-addr - - :method :url HTTP/:http-version :status :res[content-length] :referrer :user-agent'
  }));

我添加了捕获所有路由以获取/生成跟踪ID

app.all('*', function(req, res, next){
  var traceId = req.params['trace_id'];
  if(!traceId){
    traceId = require('node-uuid').v4();
  }
  req.params['trace_id'] = traceId;
});

所以问题是: 如何通过应用程序提供每个调用的唯一跟踪ID?

更新 为了确保跟踪ID始终处于使用状态,我想为每个请求创建一个全局变量,而不将变量从请求传递到控制器然后再次传递,因为这意味着每次都有新的控制器或者引入服务然后我们也必须记住跟踪ID。

1 个答案:

答案 0 :(得分:1)

我已使用continuation-local-storage结束存储trace_id,并在以后记录

时使用它

将以下内容添加到winston过滤器

logger.addFilter(function(msg, meta, level) {
   var nameSpace = require('continuation-local-storage').getNamespace('nameSpace');
   ....
   meta.trace_id = meta.trace_id || nameSpace.get('trace_id');
   return msg;
}

并将app.all()函数更改为

server.all('*', function(req, res, next) {
  var nameSpace = require('continuation-local-storage').getNamespace('nameSpace');
  var traceId = req.get(GLOBAL.com.mdsol.csa.traceIdKey);
  if (!traceId) {
    traceId = uuid.v4();
  }
  res.header('trace_id', traceId);
  nameSpace.run(function() {
    nameSpace.set('trace_id', traceId);
  });
});