Reputation: 184
I am using pinojs as logger in my nodejs server, and for each module I make a child logger for the module to add some common message There is an annoying problem is when I change base logger's loglevel, it won't effect child logger, and pino doesn't record child loggers of a specific parent logger. So I try to update every child logger's loglevel. I assign onChild function for baseLogger and it will record every child logger when created, To avoid memory leak, as WeakSet/WeakMap cannot to be iterated, I use WeakRef to store childLogger. So the first version is
const childLoggers = new Set<WeakRef<Logger>>();
baseLogger.onChild = child => {
// store ref
child.onChild = baseLogger.onChild;
const ref = new WeakRef(child);
childLoggers.add(ref);
return child;
};
I suddenly appear to know that there is a problem, although childLogger will be released correctly, but weakRef it self won't. I do some research and found FinalizationRegistry may solve my problem, then I made second version
const childLoggers = new Set<WeakRef<Logger>>();
const registry = new FinalizationRegistry<WeakRef<Logger>>(ref => {
childLoggers.delete(ref);
});
baseLogger.onChild = child => {
// store ref
child.onChild = baseLogger.onChild;
const ref = new WeakRef(child);
registry.register(ref, ref);
childLoggers.add(ref);
return child;
};
I am new to FinalizationRegistry and I am using weakRef itself as heldValue which in every example I see doesn't do it, is it safe to use? And should I pass Set as part of heldValue?
Upvotes: 0
Views: 16