【问题标题】:How to customize error stored in winston logger file如何自定义存储在 winston 记录器文件中的错误
【发布时间】:2019-11-12 18:02:47
【问题描述】:

我尝试将信息消息和错误消息存储在 winston 记录器文件中,它成功运行。但我希望将可自定义的错误存储在 winston 记录器文件中。如何解决它

winston.js

var myFormat = winston.format.combine(winston.format.timestamp({format:'YYYY-MM-DD HH:mm:ss.SSS'}),
winston.format.json())
const logger = winston.createLogger({
    level: 'info',
    format: myFormat,
    defaultMeta: { service: 'user-service' },
    transports: [
      //
      // - Write to all logs with level `info` and below to `combined.log` 
      // - Write all logs error (and below) to `error.log`.
      //
      new winston.transports.Console(),
      new winston.transports.File({ filename: 'error.log', level: 'error' }),
      new winston.transports.File({ filename: 'combined.log' })
    ],
    exceptionHandlers: [
        new winston.transports.Console(),
        new winston.transports.File({ filename: './exceptions.log', timestamp: true, maxsize: 1000000 })
      ],  
  });

  //
  // If we're not in production then log to the `console` with the format:
  // `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
  // 
  if (process.env.NODE_ENV !== 'production') {
    logger.add(new winston.transports.Console({
      format: winston.format.simple()
    }));
  }

module.exports = logger;

authentication.js

const authMiddleware = function (userPermissionLevels) {
    return (request, response, next) => {
        const token = request.header('x-auth-token');
        if (!token) return response.status(401).send("no token provided");
        const decoded = jwt.verify(token, config.get('jwtPrivateKey'));

        // Check for permissions
        if (!userPermissionLevels.includes(decoded.userPermissionLevels)) return response.status(403).send("Access denied.");

        request.user = decoded;
        next();
    }
}
I want to store "no token provided" and access deined error in winston logger file.How to acheive it.

【问题讨论】:

    标签: node.js logging winston


    【解决方案1】:

    您只需要使用创建的 winston 记录器对象并在从函数返回之前记录消息。

    const logger = require('./winston'); //assuming winston.js in the same level as authentication.js
    
    const authMiddleware = function (userPermissionLevels) {
        return (request, response, next) => {
            const token = request.header('x-auth-token');
            if (!token){ 
                logger.info('no token provided');
                return response.status(401).send("no token provided");
            }
            const decoded = jwt.verify(token, config.get('jwtPrivateKey'));
    
            // Check for permissions
            if (!userPermissionLevels.includes(decoded.userPermissionLevels)){ 
                logger.info('Access denied.');
                return response.status(403).send("Access denied.");
            }
    
            request.user = decoded;
            next();
        }
    }
    

    【讨论】:

    • 我还有一个疑问,信息消息只存储了信息文件,错误消息只存储了错误文件。如何拆分代码@Boney
    • 抱歉没找到你。我在配置中没有看到 info.log 文件。您是否希望将日志(错误和信息)存储到单独的文件 error.log 和 info.log 中?
    • Winston 只允许每个记录器传输 1 个文件,这意味着只能提及 1 个文件。您需要尝试此处提到的解决方法:stackoverflow.com/questions/10045891/…
    • @Boney 我怀疑我创建了成功创建的winston日志文件,但错误消息存储在两个(info.log,error.log)文件中。如何将错误消息存储到错误文件而不是信息文件中.
    猜你喜欢
    • 2017-03-24
    • 2021-09-14
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 2022-06-13
    • 2021-10-10
    • 2014-12-03
    • 1970-01-01
    相关资源
    最近更新 更多