如何使用Winston 3记录完整堆栈跟踪?

时间:2017-11-10 21:52:15

标签: javascript node.js logging winston

我的记录器设置如下:

dev

然后我输出了一些错误:

const myFormat = printf(info => {
   return `${info.timestamp}: ${info.level}: ${info.message}: ${info.err}`;
 });


 const logger =
   winston.createLogger({
   level: "info",
   format: combine(timestamp(), myFormat),

   transports: [
     new winston.transports.File({
     filename:
      "./logger/error.log",
        level: "error"
    }),
     new winston.transports.File({
       filename:
       "./logger/info.log",
       level: "info"
   })
  ]
})

如何通过错误传输记录错误的完整堆栈跟踪?我尝试传入err.stack,它出现了未定义。

谢谢!

7 个答案:

答案 0 :(得分:10)

您可以编写格式化程序以将error.stack传递给日志。

const errorStackFormat = winston.format(info => {
  if (info instanceof Error) {
    return Object.assign({}, info, {
      stack: info.stack,
      message: info.message
    })
  }
  return info
})

const logger = winston.createLogger({
  transports: [ ... ],
  format: winston.format.combine(errorStackFormat(), myFormat)
})

logger.info(new Error('yo')) // => {message: 'yo', stack: "Error blut at xxx.js:xx ......"} 

(输出取决于您的配置)

答案 1 :(得分:9)

@Ming的答案部分使我到了那里,但是要对错误进行字符串说明,这就是我对我们的堆栈进行全栈跟踪的方式:

import winston from "winston";

const errorStackTracerFormat = winston.format(info => {
    if (info.meta && info.meta instanceof Error) {
        info.message = `${info.message} ${info.meta.stack}`;
    }
    return info;
});

const logger = winston.createLogger({
    format: winston.format.combine(
        winston.format.splat(), // Necessary to produce the 'meta' attribute
        errorStackTracerFormat(),
        winston.format.simple()
    )
});

logger.error("Does this work?", new Error("yup"));

// The log output:
//   error: Does this work? Error: Yup
//       at Object.<anonymous> (/path/to/file.ts:18:33)
//       at ...
//       at ...

答案 2 :(得分:6)

这是我的记录器配置。由于Murli Prajapati ans和printf函数的小技巧,添加了errors({ stack: true })。我的温斯顿版本是3.2.1

const {format, transports} = require('winston');
const { timestamp, colorize, printf, errors } = format;
const { Console, File } = transports;
LoggerConfig = {
        level: process.env.LOGGER_LEVEL || 'debug',
        transports: [
            new Console(),
            new File({filename: 'application.log'})
        ],
        format: format.combine(
            errors({ stack: true }),
            timestamp(),
            colorize(),
            printf(({ level, message, timestamp, stack }) => {
                if (stack) {
                    // print log trace 
                    return `${timestamp} ${level}: ${message} - ${stack}`;
                }
                return `${timestamp} ${level}: ${message}`;
            }),
        ),
        expressFormat: true, // Use the default Express/morgan request formatting. Enabling this will override any msg if true. Will only output colors with colorize set to true
        colorize: false, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
        ignoreRoute: function (req, res) {
            return false;
        } // optional: allows to skip some log messages based on request and/or response
}

我在express-winston中使用了相同的配置,并且也用于常规日志。

const winston = require('winston');
const expressWinston = require('express-winston');

/**
 * winston.Logger
 * logger for specified log message like console.log
 */
global.__logger = winston.createLogger(LoggerConfig);
/**
 * logger for every HTTP request comes to app
 */
app.use(expressWinston.logger(LoggerConfig));

答案 3 :(得分:6)

这是Winston 3.2的另一种表现。

现在,Winston附带了一个内置的stacktrace格式化程序,但是如果将同一格式化程序组合在一起winston.format.simple(),它似乎不会触发。因此,您需要使用winston.format.printf代替Kirai Mali的回答。我不知道如何在同一配置中同时配置winston.format.errors()winston.format.simple()

基于当前的Winston README示例和上面的答案,这是我的配置,使用JSON格式的日志文件,但是对于本地开发控制台,它仍然提供彩色的日志行和良好的堆栈跟踪。


// Use JSON logging for log files
// Here winston.format.errors() just seem to work
// because there is no winston.format.simple()
const jsonLogFileFormat = winston.format.combine(
  winston.format.errors({ stack: true }),
  winston.format.timestamp(),
  winston.format.prettyPrint(),
);

// Create file loggers
const logger = winston.createLogger({
  level: 'debug',
  format: jsonLogFileFormat,
  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.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ],
  expressFormat: true,
});

// When running locally, write everything to the console
// with proper stacktraces enabled
if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format:  winston.format.combine(
                winston.format.errors({ stack: true }),
                winston.format.colorize(),
                winston.format.printf(({ level, message, timestamp, stack }) => {
                  if (stack) {
                      // print log trace
                      return `${timestamp} ${level}: ${message} - ${stack}`;
                  }
                  return `${timestamp} ${level}: ${message}`;
              }),
            )
  }));
}

答案 4 :(得分:2)

这是我的logger.jswinston": "^3.1.0

const { createLogger, format, transports } = require('winston');
const { combine, timestamp, printf, colorize, splat } = format;

const myFormat = printf((info) => {
  if (info.meta && info.meta instanceof Error) {
    return `${info.timestamp} ${info.level} ${info.message} : ${info.meta.stack}`;
  }
  return `${info.timestamp} ${info.level}: ${info.message}`;
});

const LOG_LEVEL = process.env.LOG_LEVEL || 'debug';
const logger = createLogger({
  transports: [
    new (transports.Console)(
      {
        level: LOG_LEVEL,
        format: combine(
          colorize(),
          timestamp(),
          splat(),
          myFormat
        )
      }
    )
  ]
});
module.exports = logger;

答案 5 :(得分:2)

对于Winston版本3.2.0+,以下代码将stacktrace添加到日志输出中:

import { createLogger, format, transports } from 'winston';

const { combine, timestamp, prettyPrint, colorize, errors,  } = format;


const logger = createLogger({
  format: combine(
    errors({ stack: true }), // <-- use errors format
    colorize(),
    timestamp(),
    prettyPrint()
  ),
  transports: [new transports.Console()],
});  

参考:https://github.com/winstonjs/winston/issues/1338#issuecomment-482784056

答案 6 :(得分:-2)

  

logger.error(GET on /history,{err});

err变量是错误对象吗?

如果不是 - 您可以使用new Error().stack获取跟踪,并将传递给winston。