【问题标题】:Nodejs / Express / Winston logger: how to elegantly put req.headers.username in log format?Nodejs / Express / Winston logger:如何优雅地将 req.headers.username 放入日志格式?
【发布时间】:2022-01-06 11:07:50
【问题描述】:

我的 nodejs / Express js 后端正在使用 Winston 记录器。

src/utils/logger.ts:

import winston from 'winston'
import moment from 'moment';
import os from 'os';
import process from 'process';
import request from 'express';


const levels = {
  error: 0,
  warn: 1,
  info: 2,
  http: 3,
  debug: 4,
}

const level = () => {
  return 'debug'
}

const colors = {
  error: 'red',
  warn: 'yellow',
  info: 'green',
  http: 'magenta',
  debug: 'white',
}
winston.addColors(colors)

const timezonedTime = () => {
  return moment().local().format('YYYY-MMM-DD hh:mm:ss:ms');  
}; 
   

const format_string = winston.format.combine(
  winston.format.timestamp({format: timezonedTime}),
  winston.format.colorize({ all: true }),
  winston.format.printf(
    (info) => `${info.timestamp}  ${os.hostname()} ${process.pid} ${info.level}: ${info.message}`,
  ),
)

const format_json = winston.format.combine(
  winston.format.timestamp({format: timezonedTime}),
  winston.format.colorize({ all: true }),
  winston.format.printf(
    (info) => `${info.timestamp}  ${os.hostname()} ${process.pid} ${info.level}: ${info.message}`,
  ),
  winston.format.json(),
)


const options = {
  conosle: {
    format: format_string,
    level: 'info',
    handleExceptions: true,
    json: false,
    colorize: true,
  },

  error_logfile: {
    filename: 'logs/error.log',
    level: 'error',
    format: format_string,
    handleExceptions: true,
  }, 

  all_logfile: { 
    filename: 'logs/all.log', 
    format: format_string 
  },

  all_logfile_json: { 
    filename: 'logs/all_json.log',
    format: format_json
  }

};

const transports = [
  new winston.transports.Console(options.conosle),
  new winston.transports.File(options.error_logfile),
  new winston.transports.File(options.all_logfile),
  new winston.transports.File(options.all_logfile_json),
]

const Logger = winston.createLogger({
  level: level(),
  levels,
  transports,
})

export default Logger


我的应用程序设计为只要用户登录了他的帐户,请求标头就会包含username 字段。

我想将这个username 放入由 api 端点中的函数引起的每条日志消息中。现在我在做:

/src/routes.ts:

app.get('/api/organizations/project', organizations.getProject); 

还有:

export const getProject = catchErrors( async (req, res) => {

  const username = req.header('username');
  if (!username) {
    Logger.warn(`no req.headers.username found!`);
    throw new NoUsernameError();
  }


  const user = await findUserWithOrganizationsByUsername(username);
  const userId = user.id; 
  const userType = user.userType; 
  Logger.info(`User ${req.headers.username} has id and type ${userId}, ${userType};`);


  const organizationId = req.query.organizationId; 
  
  const organization = await findEntityOrThrow(Organization, organizationId, {
    relations: ['users']
  });

  Logger.info(`User ${req.headers.username}:  got organization`);


  ...

基本上在业务逻辑代码的许多步骤中,我需要在其中记录一条带有req.headers.username 的消息,就像所有日志条目中的leveltimestamp 一样。

有没有一种优雅的方式来放置它?我不想做

Logger.info(`User ${req.headers.username}  ....bla bla bla ... `);

在每个记录器行中。

【问题讨论】:

    标签: node.js express logging winston express-winston


    【解决方案1】:

    要为每个日志事件添加一些内容,请使用defaultMeta(来自Winston docs):

    const winston = require('winston');
    
    const logger = winston.createLogger({
      level: 'info',
      format: winston.format.json(),
      defaultMeta: { service: 'user-service' },
      transports: [
        //
        // - Write all logs with importance level of `error` or less to `error.log`
        // - Write all logs with importance level of `info` or less to `combined.log`
        //
        new winston.transports.File({ filename: 'error.log', level: 'error' }),
        new winston.transports.File({ filename: 'combined.log' }),
      ],
    });
    

    要向日志事件子集添加额外的上下文,请使用child logger

    const childLogger = logger.child({ requestId: '451' });
    childLogger.info('This log will have an attached requestId');
    

    【讨论】:

      猜你喜欢
      • 2013-06-27
      • 1970-01-01
      • 2013-09-13
      • 2018-06-10
      • 2016-04-18
      • 2021-04-26
      • 2017-05-17
      • 1970-01-01
      • 2019-06-15
      相关资源
      最近更新 更多