如何自定义存储在Winston记录器文件中的错误

时间:2019-07-02 06:29:59

标签: node.js logging winston

我试图将信息消息和错误消息存储在winston logger文件中,该文件可以正常工作。但是我想将可自定义的错误存储在winston logger文件中。怎么解决

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.

1 个答案:

答案 0 :(得分:1)

您只需要使用创建的Winston logger对象并记录消息,然后从函数中返回即可。

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();
    }
}