Reputation: 722
I am working on logging helper (in Node.JS) witch have few exported functions (error, warn, etc...)
.
I have for example two other scripts what using this my "module": test1, test2
I need when I initialize my logging module (let log = require("./log.js");
) in both scripts to get error messages like this: [time][ERROR][TEST1] actual message...
I can use non-singleton approach and add constructor to my logging module what will take TEST1
so every script can have his own logger.
But when there will be 100 scripts using logger, there will also be 100 logger instances.
So is there better approach to get same result, every file CAN have his own defined prefix?
Upvotes: 1
Views: 536
Reputation: 1897
Hope this helps for some of your cases...
const log = console.log;
export default function middleWare(optionalStringExtension = '') {
console.log = (...args) => {
log(...args, optionalStringExtension);
}
}
Upvotes: 0
Reputation: 222865
The module needs to export factory function or a constructor; a parameters need to be passed somehow in order for test1
instance to be created.
Instances can be handled either by a user with modules which provide singletons naturally:
const loggerFactory = require('./log');
module.exports = loggerFactory('test1');
Or by the library itself:
loggerFactory.instances = new WeakMap();
function loggerFactory(name) {
if (!loggerFactory.instances.has(name)) {
loggerFactory.instances.set(name, ...);
}
return loggerFactory.instances.get(name);
}
The second case is exactly what renowned debug
library does, although it handles a map of instances with regular object instead of WeakMap
for compatibility reasons.
Upvotes: 1