0
我正在使用像winston,mongodb等庫的node.js。我將nodejs分割爲多個文件以便於維護,如index.js,user.js,posting.js,database.js,logging.js等。node.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爲日誌記錄,這導致記錄器的4次初始化。 我添加database.js到index.js,user.js和posting.js nd這導致數據庫的3次初始化。
這是好的或需要使記錄器和數據庫單身?