Javascript 如何使用Winston 3记录完整堆栈跟踪?
我的记录器设置如下:Javascript 如何使用Winston 3记录完整堆栈跟踪?,javascript,node.js,logging,winston,Javascript,Node.js,Logging,Winston,我的记录器设置如下: const myFormat = printf(info => { return `${info.timestamp}: ${info.level}: ${info.message}: ${info.err}`; }); const logger = winston.createLogger({ level: "info", format: combine(timestamp(), myFormat), transports:
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"
})
]
})
然后我注销了一些错误,如下所示:
logger.error(`GET on /history`, { err });
如何通过错误传输将错误的完整堆栈跟踪记录到日志中?我尝试传入err.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/14/2021-这在较新版本的Winston中不再有效 原始答案 @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 ...
从“winston”导入winston;
const errorStackTracerFormat=winston.format(信息=>{
if(info.meta&&info.meta实例错误){
info.message=`${info.message}${info.meta.stack}`;
}
退货信息;
});
const logger=winston.createLogger({
格式:winston.format.combine(
winston.format.splat(),//生成“meta”属性所必需的
errorStackTracerFormat(),
winston.format.simple()
)
});
logger.error(“这行吗?”),新错误(“是的!”);
//日志输出:
//错误:这行吗?错误:是的!
//反对。(/path/to/file.ts:18:33)
//在。。。
//在。。。
这是我的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;
对于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()],
});
从“winston”导入{createLogger,格式,传输};
const{combine,timestamp,prettyPrint,colorize,errors,}=格式;
const logger=createLogger({
格式:联合收割机(
错误({stack:true}),//这是我的记录器配置。由于printf函数中的错误和小技巧,添加了错误({stack:true})
。我的winston版本是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.2的另一个例子
现在Winston自带了一个内置的stacktrace格式化程序,但是如果同一个格式化程序组合了Winston.format.simple()
,它似乎不会触发。因此,你需要使用Winston.format.printf
,就像Kirai Mali的回答一样。我不知道如何配置这两个Winston.format.errors()
和winston.format.simple()
在相同的配置中
基于当前的Winston自述示例和上面的答案,这里是我使用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}`;
}),
)
}));
}
我注意到这是可行的,但是文档说需要将错误对象放在第二个参数中的位置是什么?@5413668060您不应该将错误对象放在第二个参数中。这是为了。如果您将错误对象作为第一个参数传递,那么您必须将info.meta.XXX
函数中的errorStackTracerFormat
引用更改为info.XXX
很抱歉,但是您的示例没有实现它所声称的功能。是的,info对象的console.dir没有显示任何meta。它显示一些splat符号。内部必须已更改。什么是myFormat
?如果我们需要记录一条消息,然后出现错误(类似于Java的log4j等):logger.error('Failed to do sth',e)
?请注意:预打印格式不应在生产中使用,因为它可能会对性能产生负面影响并阻止事件循环。