From 03e3641e0359776d853cd6d83203e85f05978445 Mon Sep 17 00:00:00 2001 From: Tiara Rodney Date: Fri, 13 Mar 2026 22:39:35 +0100 Subject: [PATCH] fix(manager): correct getLogger and implement hierarchy setup Fix inverted type check in getLogger() and add missing return statement. Implement _fixupParents() and _fixupChildren() to establish parent-child logger relationships based on dot-separated scope names. --- src/manager.ts | 73 +++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 63 insertions(+), 10 deletions(-) diff --git a/src/manager.ts b/src/manager.ts index c891849..32bc8c5 100644 --- a/src/manager.ts +++ b/src/manager.ts @@ -71,20 +71,73 @@ export class Manager { * up the parent/child references which pointed to the placeholder to now * point to the logger. */ - getLogger(scope: string) { - var rv: null|Logger = null; + getLogger(scope: string): Logger { + let rv: Logger; - if (typeof scope != 'string') { + if (scope in this.loggers) { + const existing = this.loggers[scope]; - rv = this.loggers[scope]; - - if (rv instanceof Placeholder) { - var ph = rv; - rv = new (this._loggerClass ?? loggerClass)(scope, NOTSET); - } - else { + if (existing instanceof Placeholder) { rv = new (this._loggerClass ?? loggerClass)(scope, NOTSET); this.loggers[scope] = rv; + this._fixupChildren(existing, rv); + } + else { + rv = existing; + } + } + else { + rv = new (this._loggerClass ?? loggerClass)(scope, NOTSET); + this.loggers[scope] = rv; + this._fixupParents(rv); + } + + return rv; + } + + /** + * Ensure that there are either loggers or placeholders all the way from + * the specified logger to the root of the logger hierarchy. + */ + protected _fixupParents(logger: Logger) { + const name = logger.scope; + let i = name.lastIndexOf('.'); + let rv: Logger | null = null; + + while (i > 0 && !rv) { + const substr = name.substring(0, i); + + if (!(substr in this.loggers)) { + this.loggers[substr] = new Placeholder(logger) as unknown as Logger; + } + else { + const obj = this.loggers[substr]; + + if (obj instanceof Placeholder) { + obj.push(logger); + } + else { + rv = obj; + } + } + + i = name.lastIndexOf('.', i - 1); + } + + (logger as unknown as { parent: Logger }).parent = rv ?? this.root; + } + + /** + * Ensure that children of the placeholder ph are connected to the + * specified logger. + */ + protected _fixupChildren(ph: Placeholder, logger: Logger) { + const name = logger.scope; + + for (const c of ph.loggers) { + if (c.parent!.scope.substring(0, name.length) !== name) { + (logger as unknown as { parent: Logger }).parent = c.parent!; + (c as unknown as { parent: Logger }).parent = logger; } } }