我正在使用Winston作为NodeJS项目的记录器。我尝试将时间戳添加到日志消息中并配置Winston以非Json方式编写控制台日志消息未成功。我的配置如下
const appRoot = require('app-root-path');
const winston = require('winston');
const options = {
file: {
level: 'info',
filename: `${appRoot}/logs/app.log`,
timestamp: true,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 15,
colorize: false,
},
console: {
level: 'debug',
timestamp: true,
handleExceptions: true,
json: false,
colorize: true,
},
};
const logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
new winston.transports.Console(options.console)
],
exitOnError: false,
});
module.exports = logger;
这就是我将Winston导入其他文件的方式(winston配置文件位于我的项目的根目录中):
const winston = require('../winston');
关于它为什么起作用的任何想法吗?
答案 0 :(得分:2)
我在winston 3中遇到了此错误。请看this section中的文档,该文档指定了记录器的格式。这样可以解决问题。
答案 1 :(得分:1)
以下是带有时间戳的可正常工作的Winston记录器模块:
const { createLogger, format, transports } = require("winston");
const { combine, timestamp, label, printf } = format;
const appRoot = require("app-root-path");
const myFormat = printf(({ level, message, label, timestamp }) => {
return `${timestamp} ${level}: ${message}`;
});
const options = {
file: {
level: "info",
filename: `${appRoot}/logs/app.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
timestamp: true,
},
console: {
level: "debug",
handleExceptions: true,
json: false,
colorize: true,
},
};
const logger = createLogger({
format: combine(label({ label: this.level }), timestamp(), myFormat),
transports: [new transports.Console(options.console), new transports.File(options.file)],
});
module.exports = logger;
答案 2 :(得分:0)
以下是帮助在输出(日志文件,控制台)上打印时间戳的示例。
此示例使用的版本:
├──快递@ 4.17.1 ├──express-async-errors@3.1.1 └──winston@3.3.3
// Declare winston
const winston = require("winston");
// Import all needed using Object Destructuring
const { createLogger, format, transports } = require("winston");
const { combine, timestamp, printf } = format;
// Export the module
module.exports = function (err, req, res, next) {
const logger = createLogger({
level: "error",
format: combine(
format.errors({ stack: true }), // log the full stack
timestamp(), // get the time stamp part of the full log message
printf(({ level, message, timestamp, stack }) => { // formating the log outcome to show/store
return `${timestamp} ${level}: ${message} - ${stack}`;
})
),
transports: [
new transports.Console(), // show the full stack error on the console
new winston.transports.File({ // log full stack error on the file
filename: "logfile.log",
format: format.combine(
format.colorize({
all: false,
})
),
}),
],
});
logger.log({
level: "error",
message: err,
});
// Response sent to client but nothing related to winston
res.status(500).json(err.message);
};