我正在使用节点js创建一个测试应用程序,我需要为winston和morgan提供单独的logger js文件。我为winston创建了单独的文件,并且工作正常,但是我没有得到如何为摩根记录器创建相同的文件。
我的morganLogger.js看起来像
var morgan = require('morgan');
var accessLogDirectory = __dirname + '/accessLog';
var fs = require('fs');
var path = require('path');
var fileStreamRotator = require('file-stream-rotator');
//ensure log directory exists for acccess log
fs.existsSync(accessLogDirectory) || fs.mkdirSync(accessLogDirectory)
//use custom token for date
morgan.token('date', function () {
return new Date();
});
//create a rotating write stream
var accessLogStream = fileStreamRotator.getStream({
filename: accessLogDirectory + '/access-%DATE%.log',
frequency: 'daily',
verbose: false,
date_format: 'YYYYMMDD'
});
morgan.stream = accessLogStream;
morgan.format = ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]';
module.exports = morgan;
我的server.js看起来像这样,
var express = require('express');
var morganLogger = require('./utility/morganLogger.js');
var routes = require('./routes/index');
var users = require('./routes/users');
app.use(morganLogger());
app.use('/', routes);
运行代码后,我登录调试器但未创建日志文件。
答案 0 :(得分:0)
按morgan()
调用morgan时,您可以通过传递morgan('options')
之类的对象来设置stream
之类的参数{ stream: accessLogStream }
。
在实例化morgan,var morganLogger = require('./utility/morganLogger.js');
并调用实例化app.use(morganLogger());
时,尝试传递这样的参数:
// in morganLogger.js
morgan.format = ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]';
morgan.options = {
stream: accessLogStream
};
// in server.js
app.use(morganLogger (mormorganLogger.format, morganLogger.options));
// also in morganLogger.js use path.join
// when instantiating accessLogDirectory
var accessLogDirectory = path.join(__dirname ,'/accessLog');