我正在查看顶级 Node 日志记录系统:npmlog
、log4js
、bunyan
和 winston
,并决定使用 winston
获得最多的每月 npm
下载量。
我要设置的是自定义记录器,我将能够在开发环境中使用 logger.debug(...)
它不会在生产环境中记录任何内容。这将对我有所帮助,所以当我在开发环境中时,我不需要写任何东西,因为我会看到所有的输出。
这就是我现在拥有的:
var level = 'debug';
if (process.env.NODE_ENV !== 'development'){
level = 'production'; // this will never be logged!
}
var logger = new winston.Logger({
transports: [
// some other loggings
new winston.transports.Console({
name: 'debug-console',
level: level,
prettyPrint: true,
handleExceptions: true,
json: false,
colorize: true
})
],
exitOnError: false // don't crush no error
});
当我尝试记录 JavaScript Object
或 Javascript Array
时出现问题。使用 Object
,我需要执行 toJSON()
,而对于 Array
,我首先需要 JSON.stringify()
然后是 JSON.parse()
.
一直写这些方法并不好,只是为了记录我想要的东西。此外,它甚至对资源都不友好,因为这些格式化方法需要在 logger.debug()
意识到它在生产中并且它不应该首先记录它之前执行(基本上,它在函数调用之前评估参数)。我只是喜欢老式 console.log()
记录 JavaScript 对象和数组的方式。
现在,在我写这个问题时,我发现有一种描述 custom format 的方式。对于每个 winston transsports
对象。是这样做的方式,还是有其他的方式?
最佳答案
logger.log("info", "Starting up with config %j", config);
Winstons 使用内置的 utils.format 库。 https://nodejs.org/dist/latest/docs/api/util.html#util_util_format_format_args
关于javascript - 如何像 console.log 一样在 winston 中记录 JavaScript 对象和数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33158974/