javascript 如何使用 Winston 3 记录完整的堆栈跟踪?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47231677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Log Full Stack Trace with Winston 3?
提问by Anthony Xie
My logger is set up like:
我的记录器设置如下:
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"
})
]
})
Then I am logging out some error like this:
然后我注销了一些这样的错误:
logger.error(`GET on /history`, { err });
How is it possible to log the full stack trace for errors to via the error transport? I tried passing in the err.stack and it came out as undefined.
如何通过错误传输记录错误的完整堆栈跟踪?我尝试传入 err.stack,但结果未定义。
Thanks !
谢谢 !
回答by Ming
You can write a formatter to pass error.stackto log.
您可以编写一个格式化程序来传递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 ......"}
(the output will depend on your configuration)
(输出将取决于您的配置)
回答by Mike Richards
@Ming's answer got me partly there, but to have a string description with the error, this is how I got full stack tracing working on ours:
@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' property
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 ...
回答by Murli Prajapati
For winston version 3.2.0+, following will add stacktrace to log output:
对于 winston 版本3.2.0+,以下将向日志输出添加堆栈跟踪:
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()],
});
Ref: https://github.com/winstonjs/winston/issues/1338#issuecomment-482784056
参考:https: //github.com/winstonjs/winston/issues/1338#issuecomment-482784056
回答by vanduc1102
Here is my logger.jswith winston": "^3.1.0
这是我logger.js的winston": "^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;
回答by Kiran Mali
Here is my logger configuration. Added errors({ stack: true }), thanks to Murli Prajapati ansand small trick in printf function. My winston version is 3.2.1.
这是我的记录器配置。添加errors({ stack: true }),感谢Murli Prajapati ans和 printf 函数中的小技巧。我的温斯顿版本是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
}
I am using this same configuration in express-winstonand for general log also.
我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));
回答by Mikko Ohtamaa
Here is another take for Winston 3.2.
这是 Winston 3.2 的另一个版本。
Nowadays Winston comes with a built-in stacktrace formatter, but it does not seem to trigger if the same formatter has winston.format.simple()combined. Thus, you need use winston.format.printfinstead as by the answer from Kirai Mali. I could not figure out how to configure both winston.format.errors()and winston.format.simple()in the same configuration.
现在 Winston 带有内置的堆栈跟踪格式化程序,但如果winston.format.simple()组合了相同的格式化程序,它似乎不会触发。因此,您需要使用winston.format.printfKirai Mali 的回答。我无法弄清楚如何配置都winston.format.errors()和winston.format.simple()在相同的配置。
Based on the current Winston README example and answers above, here is my configuration that uses JSON format logfiles, but for the local development console it still gives colored log lines and good stack traces.
基于当前的 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}`;
}),
)
}));
}

