简体   繁体   中英

How do you log an error object to file rather than console in Winston?

Is there an easy way in Winston to log a full error object to the JSON log file, but have an easily readable message printed to the console (err.message)/ 'Error Error!' in this instance?

logger.log({
    level: 'error',
    message: 'Error Error!',
    error: err
})

Currently, when I run this code I get the message plus the complete error object printed to the console. When in reality I just want the message printed to the console and then the full object available in my log files.

I also tried:

logger.error('Error Error', { error: err })

Config

import winston from 'winston'
export const logger = winston.createLogger({
    level: 'info',
    format: winston.format.json(),
    transports: [
        new winston.transports.File({ filename: './logs/error.log', level: 'error' }),
        new winston.transports.File({ filename: './logs/combined.log' })
    ]
})

if (process.env.NODE_ENV !== 'production') {
    logger.add(
        new winston.transports.Console({
            format: winston.format.combine(winston.format.colorize(), winston.format.simple())
        })
    )
}

You are currently using winston.format.simple() , which returns logs in the format of ${info.level}: ${info.message} JSON.stringify({ ...rest }) (see here https://www.npmjs.com/package/winston#usage )

You need to create your own format to generate the output you desire:

if (process.env.NODE_ENV !== 'production') {

    const myFormat = winston.format.printf(({ level, message, label, timestamp }) => {
      return `${timestamp} [${label}] ${level}: ${message}`; // modify as needed
    });

    logger.add(
        new winston.transports.Console({
          format: winston.format.combine(
            winston.format.colorize(),
            myFormat
          )
        })
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM