我尝试使用Winston为我的快速服务器设置访问日志和错误日志,但我似乎做错了。
以下是我对配置文件的尝试:
const winston = require('winston'),
fs = require('fs');
const tsFormat = () => (new Date()).toLocaleTimeString();
winston.loggers.add('errorLog', {
file: {
filename: '<path>/errors.log', //<path> is replaced by the
timestamp: tsFormat, //absolute path of the log
level: 'info'
}
});
winston.loggers.add('accessLog', {
file: {
filename: '<path>/access.log', //same as before
timestamp: tsFormat,
level: 'info'
}
});
这就是我将其包含在我的其他文件中的方式:
var winston = require('winston'),
accessLog = winston.loggers.get('accessLog'),
errorLog = winston.loggers.get('errorLog');
在我看来,这跟文档一样(https://github.com/winstonjs/winston/tree/2.4.0#working-with-multiple-loggers-in-winston) 但是当我尝试登录它时,我收到了这个错误:
[winston] Attempt to write logs with no transports {"message":"pls","level":"info"}
[winston] Attempt to write logs with no transports {"message":"Bad request: undefined","level":"warn"}
任何帮助都会非常感激,我已经被困了好几天了。
答案 0 :(得分:6)
我会尝试这样的事情,将所有与记录器相关的东西放入模块logger.js中:
<强> logger.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');
您应该看到如下日志行:
errors.log:
{"level":"info","message":"Test access log","timestamp":"2018-03-14T07:51:11.185Z"}
的access.log:
{"level":"info","message":"Test error log","timestamp":"2018-03-14T07:51:11.182Z"}
修改强>
在Winston上一版中,
new (winston.Logger)
已替换为winston.createLogger
(https://github.com/bithavoc/express-winston/issues/175)
答案 1 :(得分:1)
1个Logger +控制台日志用于开发目的:
logger.js
var logPath = '';
var log_level = '';
const log = winston.createLogger({
level: log_level,
format: winston.format.json(),
transports: [
new winston.transports.File({
filename: path.join(logPath, 'access.log'),
timestamp: tsFormat,
level: log_level
}),
new winston.transports.File({
filename: path.join(logPath, 'error.log'),
timestamp: tsFormat,
level: 'error'
}),
]
});
if (process.env.NODE_ENV !== 'production') {
log.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
module.exports = {
log: log
};
app.js
const logger = require('./logger');
logger.log.info("starting application..");
答案 2 :(得分:-1)
由于您在原始代码中将winston
变量创建为const winston
,因此无法在下面的行中添加传输和其他选项。提出的解决方案将类似的代码移至模块中,但将winston
变量分配给var winston
。