我有以下记录器模块:
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, label, printf, colorize } = format;
const logger = require('winston');
const { red } = require('colors')
const myFormat = printf(info => {
return `${info.timestamp} [${info.label}] ${info.level}:
${info.message}`;
});
module.exports = logger.createLogger({
level: 'silly',
format: combine(
label({ label: 'mylogger1' }),
timestamp(),
myFormat,
//logger.format.json(),
),
transports: [
new logger.transports.File({ filename: 'error.log', level: 'error' }),
new logger.transports.Console({
format: combine(
myFormat
)}
)
]
});
然后我在另一个文件中使用它:
const myLogger = require('./loggermodule');
myLogger.log("verbose","an error occurred in this file: " +
module.filename);
您可以看到我正在使用module.filename记录正在发生日志的文件的名称。
我想知道是否有更好的方法可以达到相同的结果
答案 0 :(得分:0)
通常,当引发错误时,在堆栈跟踪中指定文件名:
try {
} catch (e) {
logger.error(e.stack); // log stack
}
但是,如果您需要自己指定文件名,则可以创建一个包装函数,如:
/// const winston = require('winston');
const logger = winston.createLogger({
// ...
});
logger.prototype.logFilename = function (level, filename, message = "") {
logger.log(level, "An error occurred in this file", filename, message);
}
module.exports = logger;
然后:
const myLogger = require('./loggermodule');
myLogger.logFilename("verbose", module.filename);