如何在winston logger中为每个日志添加会话ID

时间:2017-11-22 10:00:59

标签: node.js winston

在我的节点应用程序中,我使用winston模块存储我的应用程序日志。我得到的日志为:

2017-11-22T07:16:38.632Z - info: asset type is attached successfully

现在我想在时间戳之后添加sessionID。我希望我的日志为:

 2017-11-22T07:16:38.632Z -**sessionId here**- info: asset type is attached successfully.

我用于winston日志记录的代码是:

var winston = require('winston');
require('winston-daily-rotate-file');
const levels = {
  error: 0,
  warn: 1,
  info: 2,
  http: 3,
  verbose: 4,
  debug: 5,
  silly: 6,
  trace: 7
};

var transport = new (winston.transports.DailyRotateFile)({
  filename: 'logs/./log',
  datePattern: 'yyyy-MM-dd.',
  prepend: true,
  json: false,
  level: process.env.ENV === 'development' ? 'debug' : 'info'
});

var logger = new (winston.Logger)({
  levels: levels,
  transports: [
    transport
  ]
});

module.exports = logger;

3 个答案:

答案 0 :(得分:0)

您必须自定义日志格式https://github.com/winstonjs/winston/tree/2.x#custom-log-format

首先更新您的运输:

var transport = new (winston...
  ...
  level: process.env.ENV === 'development' ? 'debug' : 'info',
  timestamp: () => {
    let today = new Date();
    return today.toISOString();
  },
  formatter: options => `${options.timestamp()} -${options.meta.sessionId}- ${options.level}: ${options.message}`
});

然后,只需将会话ID传递给记录器功能:

logger.info('asset type is attached successfully', {sessionId: 'mySessionID'});

你得到了

  

2017-11-22T14:13:17.697Z -mySessionID- info:资产类型已成功附加

编辑:而不是仅导出winston.logger对象,我们导出一个需要sessionId作为参数的对象,并包含winston.logger。我们还更新了传输,因此我们在新的Logger对象中自定义其 formatter 属性。在 formatter 属性中,我们将 meta 声明替换为新的 this.sessionId 变量,因此我们不使用属性。

logger.js:

var transport = new (winston...
  ...
  level: process.env.ENV === 'development' ? 'debug' : 'info',
  timestamp: () => {
    let today = new Date();
    return today.toISOString();
  }
});

class Logger {
  constructor(session) {
    this.sessionId = session;
    this.transport = transport;
    this.transport.formatter = options => `${options.timestamp()} -${this.sessionId}- ${options.level}: ${options.message}`;
    this.logger = new (winston.Logger)({
      levels: levels,
      transports: [this.transport]
    });
  }
}

module.exports = Logger;

server.js:

const Logger = require('./logger.js');
let logman = new Logger('my_session_id');
let logger = logman.logger;

logger.info('asset type is attached successfully');

  

2017-11-23T13:13:08.769Z -my_session_id- info:资产类型已成功附加

答案 1 :(得分:0)

我有同样的要求,对解决方案并不满意......我喜欢标准记录器格式化日志的方式,并且不想重新发明那个轮子。此外,我希望更紧凑的东西,我想我找到了它。我不是一个javascript程序员,所以它可能不是很好的编码练习,但它似乎对我有用...

server.js

//Initiate winston logging please
const logger = require('winston');
const common = require('winston/lib/winston/common');

function myFormat(options) {
  options.formatter = null
  options.label = helpers.getSessionId(logger.req)
  return common.log(options);
}

var consoleLoggingConfig = {
  timestamp: true,
  level: process.env.LOG_LEVEL ? process.env.LOG_LEVEL : "info",
  handleExceptions: true,
  humanReadableUnhandledException: true,
  formatter: myFormat
}

logger.remove(logger.transports.Console);
logger.add(logger.transports.Console, consoleLoggingConfig)
logger.info('Winston logging initiated', consoleLoggingConfig)

//Helper to ensure that logger has access to the request object to obtain the session id
app.use(helpers.attachReqToLogger)
module.exports=logger

helpers.js

// Helper to ensure that the winston logger has the request object on it to obtain the sessionId
helpers.attachReqToLogger = function(req, res, next) {
  logger.req = req
  next();
}

答案 2 :(得分:0)

import winston from "winston";
import { v4 as uuidv4 } from "uuid";

const { format } = winston;

const commonFormat = [format.timestamp(), format.json()];

const withId = [
    format.printf(({ message, id, ...rest }) => {

        return JSON.stringify(
            {
                // if frontend privide id, use it, else create one
                id: id ?? uuidv4(),
                message,
                ...rest,
            },
            null,
            // prettyPrint seems will overload printf's output
            // so i mannually do this
            4,
        );
    }),
];

export const logger = winston.createLogger({
    level: "debug",
    format: format.combine(...commonFormat, ...withId),
    // ...