Ant*_*Xie 23 javascript logging node.js 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: [
new winston.transports.File({
filename:
"./logger/error.log",
level: "error"
}),
new winston.transports.File({
filename:
"./logger/info.log",
level: "info"
})
]
})
Run Code Online (Sandbox Code Playgroud)
然后我正在注销一些这样的错误:
logger.error(`GET on /history`, { err });
Run Code Online (Sandbox Code Playgroud)
如何通过错误传输将错误的完整堆栈跟踪记录下来?我尝试传入err.stack,它出现了未定义.
谢谢 !
Mur*_*ati 25
对于 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()],
});
Run Code Online (Sandbox Code Playgroud)
参考:https : //github.com/winstonjs/winston/issues/1338#issuecomment-482784056
Min*_*ing 13
您可以编写一个格式化程序来传递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 ......"}
Run Code Online (Sandbox Code Playgroud)
(输出将取决于您的配置)
Mik*_*rds 12
@ 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 ...
Run Code Online (Sandbox Code Playgroud)
这是 Winston 3.2 的另一个例子。
现在 Winston 带有内置的堆栈跟踪格式化程序,但如果winston.format.simple()组合了相同的格式化程序,它似乎不会触发。因此,您需要使用winston.format.printfKirai 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}`;
}),
)
}));
}
Run Code Online (Sandbox Code Playgroud)
这是我的记录器配置。添加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
}
Run Code Online (Sandbox Code Playgroud)
我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));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9611 次 |
| 最近记录: |