better-logging
Version:
better-logging is a drop in replacement for the default logging methods of node.js
65 lines (62 loc) • 2.34 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoggerContext = void 0;
const decorateObject_1 = require("./decorateObject");
const config_1 = require("./config");
const configCache_1 = require("./configCache");
class LoggerContext {
constructor(implementation, fs) {
/*
We need to dereference the implementation object.
Since we would end up in an infinite loop if
the implementation object and the decorate target
was the same object. As in the default usecase:
const CustomInstance = (implementation) => {
const instance = new LoggerContext(implementation);
return instance.decorate.bind(instance);
}
const betterLogging = CustomInstance(console);
betterLogging(console);
console.log();
Callstack (not really, but it hammers home the point):
access :: call
-> console.log :: console.log()
-> implementation.log :: console.log()
-> implementation.log :: console.log()
-> implementation.log :: console.log()
-> implementation.log :: console.log()
...
*/
this.fs = fs;
const implementationArray = [implementation]
.flatMap((v) => v)
.map((impl) => ({
// Dereference implementation objects
log: impl.log,
info: impl.info,
warn: impl.warn,
error: impl.error,
debug: impl.debug,
}));
const handler = (type) => (...args) => {
implementationArray.forEach((impl) => {
const func = impl[type];
func(...args);
});
};
this.implementation = {
log: handler('log'),
info: handler('info'),
warn: handler('warn'),
error: handler('error'),
debug: handler('debug'),
};
}
decorate(target, config = {}) {
const patchedConfig = (0, config_1.resolveConfig)(config);
(0, decorateObject_1.decorateObject)(target, this.implementation, this.fs, patchedConfig);
configCache_1.ConfigCache.setConfig(target, patchedConfig);
return true;
}
}
exports.LoggerContext = LoggerContext;
;