我会尝试这样的方法,将所有与记录器相关的内容放入模块 logger.js 中:
记录器.js
var winston = require('winston');
var path = require('path');
// Set this to whatever, by default the path of the script.
var logPath = __dirname;
const tsFormat = () => (new Date().toISOString());
const errorLog = winston.createLogger({
transports: [
new winston.transports.File({
filename: path.join(logPath, 'errors.log'),
timestamp: tsFormat,
level: 'info'
})
]
});
const accessLog = winston.createLogger({
transports: [
new winston.transports.File({
filename: path.join(logPath, 'access.log'),
timestamp: tsFormat,
level: 'info'
})
]
});
module.exports = {
errorLog: errorLog,
accessLog: accessLog
};
然后在index.js中测试:
index.js
var logger = require('./logger');
logger.errorLog.info('Test error log');
logger.accessLog.info('Test access log');
您应该看到如下日志行:
错误日志:
{"level":"info","message":"Test access log","timestamp":"2018-03-14T07:51:11.185Z"}
访问日志:
{"level":"info","message":"Test error log","timestamp":"2018-03-14T07:51:11.182Z"}
EDIT
在 Winston 版本 3.x.x 上,new (winston.Logger)
已被替换为winston.createLogger
(https://github.com/bithavoc/express-winston/issues/175 https://github.com/bithavoc/express-winston/issues/175)