所以我正在尝试从 Winston 2.x 迁移到 3.x,但是它在设置传输方面发生了相当大的变化,我似乎无法按照之前的设置方式工作,更不用说改进它了。 我在控制台中想要什么
[human-readable-date] [level(colourised)] : [text string], [formatted JSON]
在 2.4 中,我打印了 JSON,未格式化,这就足够了,但改进总是好的。
这是我的旧配置文件
const winston = require("winston");
require("winston-mongodb");
const config = require("./mongoDb").config;
const url = config.URL;
const tsFormat = () =>
`${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`;
const logger = new winston.Logger({
transports: [
new winston.transports.Console({
timestamp: tsFormat,
colorize: true
}),
new winston.transports.MongoDB({
timestamp: tsFormat,
db: url,
level: "debug",
autoReconnect: true
})
]
});
module.exports = logger;
--编辑--
这是我现在的位置
const winston = require("winston");
require("winston-mongodb");
const config = require("./");
const mongo = require("./mongo");
const logger = winston.createLogger({
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.timestamp({
format: "YYYY-MM-DD HH:mm:ss"
}),
winston.format.align(),
winston.format.printf(
info => `${info.timestamp} ${info.level}: ${info.message}`
)
)
}),
new winston.transports.MongoDB({
db: `${config.mongoURI}/${config.mongodb}`,
level: "debug",
tryReconnect: true,
storeHost: true
})
]
});
module.exports = logger;
但是我根本无法让所需的 JSON 部分工作,也无法将其发送到 mongodb
最佳答案
取得了与我喜欢的本地风格相似的结果 pino-pretty
.
能够打印出错误堆栈和其他元数据对象。
代码:
I added an additional custom field for a namespace because my app creates a child logger for each file rather then exposing the "root" logger using
logger.child({ label: namespace })
winston.format.combine(
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
winston.format.errors({ stack: true }),
winston.format.colorize(),
winston.format.printf(
({ timestamp, level, label, message, stack, ...rest }) => {
const namespace = label ? `(${label})` : ''
const errStack = stack ? `\n${stack}` : ''
const meta =
rest && Object.keys(rest).length
? `\n${JSON.stringify(rest, undefined, 2)}`
: ''
return `[${timestamp}] ${level}: ${namespace} ${message} ${meta} ${errStack}`
}
)
)
结果:
关于javascript - 将 Winston Logger 从 2.4.4 迁移到 3.x...新的传输让我迷路了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52992042/