我正在使用node.js和winston,mongodb等库。我将nodejs拆分为多个文件,以便于维护,如index.js,user.js,posting.js,database.js,logging.js等。
logging.js如下所示:
var config = require('./config'),
path = require ('path'),
winston = require('winston'),
winstonRotate = require('winston-daily-rotate-file');
winston.level = config.appSetting.winstonLogLevel;
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winstonRotate)({
name: 'info-file',
datePattern: '.yyyyMMdd',
filename: path.join(__dirname, "logs", "info.log"),
level: 'info'
}),
new (winstonRotate)({
name: 'error-file',
datePattern: '.yyyyMMdd',
filename: path.join(__dirname, "logs", "error.log"),
level: 'error'
}),
new (winstonRotate)({
name: 'debug-file',
datePattern: '.yyyyMMdd',
filename: path.join(__dirname, "logs", "debug.log"),
level: 'debug'
}),
new (winstonRotate)({
name: 'warn-file',
datePattern: '.yyyyMMdd',
filename: path.join(__dirname, "logs", "warn.log"),
level: 'warn'
})
]
});
module.exports = logger;
database.js
var mongoClient = require('mongodb').MongoClient,
mongodbObjectID = require('mongodb').ObjectID,
logger = require('./logging'), database;
// Connect to the db
mongoClient.connect(config.appSetting.dbConnectionString, function(err, db) {
if(!err) {
database = db;
logger.info("Connected to DB");
} else {
logger.error("Failed to connect to moolahome mongodb : " + err);
console.dir(err);
process.exit(1);
}
});
module.exports = database;
我将logging.js添加到index.js,user.js和posting.js以及database.js进行日志记录,这导致logger初始化4次。 我将database.js添加到index.js,user.js和posting.js这导致3次初始化数据库。
这是正常还是需要将记录器和数据库设置为单例?