我有一个 winston 记录器,我想将执行记录器的文件的文件名设置为记录器信息对象的标签对象。例如:
[info]:[callingFileName.js] - 19.06.2019 14:09:19: [message]:...
这是我的代码:
'use strict';
const { createLogger, format, transports } = require('winston');
const winston = require('winston');
const path = require('path');
var appRoot = require('app-root-path');
const { splat, combine, timestamp, colorize, printf, label } = winston.format;
const o = {
a: [1, 2, [[
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' +
'eiusmod tempor incididunt ut labore et dolore magna aliqua.',
'test',
'foo']], 4],
b: new Map([['za', 1], ['zb', 'test']])
};
var options = {
debugfile: {
level: 'debug',
filename: `${appRoot}/logs/debug.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
},
errorfile: {
level: 'error',
filename: `${appRoot}/logs/error.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
},
console: {
colorize: true,
handleExceptions: true,
prettyPrint: true,
json: true,
}
};
const customFormat = printf(info => `[${info.level}]:[${info.label}] - ${info.timestamp}: [message]: ${info.message} ${info.meta? JSON.stringify(info.meta) : ''}`);
const simplelogger = createLogger({
name: "debug-console",
format: combine(
colorize({all:false}),
timestamp({
format: 'DD.MM.YYYY HH:mm:ss'
}),
label({
label: path.basename(process.mainModule.filename)
}),
splat(),
customFormat
),
transports: [
new transports.Console(options.console),
new transports.File( options.errorfile),
new transports.File( options.debugfile)
]
});
标签部分在这里:
label({ label: path.basename(process.mainModule.filename) }),
但我有一个问题,当我启动我的程序时,我运行npm run index.js
,所以它总是将调用文件记录为 index.js 标签:[info]:[index.js] - 19.06.2019 14:09:19: [message]: ...
。是否可以以某种方式将标签动态设置为我运行logger.log()
函数的文件名?还是每次我在 index.js 以外的新文件中时都必须创建一个新的类/实例?
编辑:我切换到 npm logat 模块,它立即用 3 行代码解决了我的问题。但是,winston 有什么简单的解决方案吗?我刚刚看到我不再需要使用 logat 的 winston。