【问题标题】:Winston/Node.js how to add a Transport only for a certain routes?Winston/Node.js 如何仅为特定路线添加传输?
【发布时间】:2020-01-03 18:09:29
【问题描述】:

假设我有以下 API 及其各自的路由如下 -

1) /api/v1/teachers - 用于教师的CRUD操作

2) /api/v1/students - 用于学生的CRUD操作

目前,我将两个 API 请求的日志存储在 combine.log 文件中。我想将教师的CRUD操作日志存储在teacher.log文件中,并将学生的CRUD操作日志存储在students.log文件中。

我提到了以下问题,作者想根据特定环境存储特定日志。

Winston/Node.js how add a Transport only for certain environment?

const winston = require('winston');
const transports = [
    new winston.transports.Console({
        level    : 'info',
        colorize : true
    }),
    new winston.transports.File({
        level    : 'info',
        filename : './logs/logs.log'
    })
];

if (process.env.NODE_ENV === 'production') {
    const Mail = require('winston-mail').Mail;

    transports.push(new Mail({
        to       : 'xxxxxx@xxxxxx.xx',
        from     : 'winston@xxxxx.xx',
        subject  : 'Errors occurred',
        level    : 'error',
        host     : 'smtp.xxxxx.xx',
        username : 'xxxx@xxxx.xx', 
        password : 'xxxxx',
        port     : 1234
    }));
}
const logger = new winston.Logger({
    transports
});

但由于我无法在 winston.js 中访问请求对象本身,因此我无法应用基于条件的路由将不同路由的日志存储在不同的文件中。

【问题讨论】:

    标签: node.js express winston morgan


    【解决方案1】:

    您可以创建 2 个传输并使用 express-winston 在路由器之前选择指定的传输。

    var router = require('./teachers-router');
    
    app.use(expressWinston.logger({
      transports: [
        new winston.transports.teachers, // you will need to create this one by your own
      ],
    }));
    app.use(router); 
    

    【讨论】:

      猜你喜欢
      • 2016-08-07
      • 2012-05-03
      • 1970-01-01
      • 2018-07-30
      • 1970-01-01
      • 2018-06-22
      • 2023-03-28
      • 2012-12-31
      • 2023-03-13
      相关资源
      最近更新 更多