我应该在哪个文件中初始化Express.js中的对象?
我是Node.js和Express的新手。
我想使用log4js,但不确定在哪个文件我应该configuration我的logging器。
是否有一个传统的文件进行初始化? 如果没有,我应该在哪里创build一个新的configuration文件?
谢谢 :)
回答(基于@ jfriend00的答案)
在logger.js
'use strict'; var log4js = require('log4js'); log4js.configure({ "appenders": [...] }); var logger = log4js.getLogger("structuredLogger"); module.exports = logger
在client.js
var logger = require('../../../../../config/logger.js'); logger.info('My message');
这个模块将允许我:
- 轻松configurationlog4js
- 用另一个软件包轻松replacelog4js。
需要初始化一个模块的一个常见选项是创build自己的容器模块来进行初始化。 然后,每个想要使用日志logging的模块都可以加载你的容器模块,如果尚未初始化,容器模块将初始化日志logging。
// mylog.js // initialization code will only be called the first time the module is loaded // after that, the module is cached by the `require()` infrastructure var log4js = require('log4js'); log4js.configure({ appenders: [ { type: 'console' }, { type: 'file', filename: 'logs/cheese.log', category: 'cheese' } ] }); module.exports = log4js;
然后,每个希望使用通用configuration日志logging的模块都可以在模块的顶部附近执行此操作:
var log4js = require('./mylog.js');