我是新来的
Node.js
还有javascript,所以我仍然在学习输入输出。我来自巨蟒的背景。
我有一个可导入的函数,它创建一个日志记录器,并将日志对象复制回
main
脚本。
我正在将其他模块导入
主要的
脚本,我希望它们使用相同的日志对象/设置。
在python中,logger对象是一个单实例,当从下标或导入的方法再次实例化时,它将获取所有现有的传输。
在JS中也可以这样做,而不必通过
logger
对象作为函数的参数?
记录器.js
const { createLogger, transports } = require("winston");
let { format } = require("winston");
let logger;
let log_level;
let logfile;
let screendump;
function formatParams(info) { (...snip...) }
//Set format default here
format = format.combine( ...snip ...);
module.exports = {
set: function (argv) { // defaults
/* Set logging. Can be set by command line or config file */
var log_level = ( process.env.log_level != null ? process.env.log_level : argv["log_level"] ) // Can end as undefined
var logfile = ( process.env.logfile != null ? process.env.logfile : argv["logfile"] ) // Can end as undefined
var screendump = ( process.env.screendump != null ? process.env.screendump : argv["screendump"]) // Can end as undefined
// Put a check in here to ensure "formatting" is a format object
if ( typeof formatting !== 'undefined') { format = formatting; }
logger = createLogger({
level : log_level,
format: format,
transports: [
// Start with everything going to dev null...just to satisfy
// Winston's requirement for at least one transport.
// Add more later
new transports.File({ filename: '/dev/null', level: 'error' }),
]
});
// put a file check in here
if ( typeof logfile !== 'undefined' ) {
logger.add(new transports.File({ filename: logfile, format: format }) )
}
if ( typeof screendump !== 'undefined' || screendump != false) {
logger.add(new transports.Console({ format: format }) );
}
return logger;
},
};
主.js
var log = require('./logger');
require('./mySubFunction')();
logger = log.set(argv);
logger.log('info',"Logger successfully started!");
mySubFunction(param = 10);
mysubfunction.js版本
logger = <import existing logger object created by main?>
module.exports = function() {
this.mySubFunction = function (param) { // defaults
var i;
for (i = 0; i < param; i++) {
logger.log('info', "This is iteration" + String(i));
}
return;
}
}