From a91c4a48251ee7841b7cfc2ac24096ccc574ca09 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Tue, 7 May 2024 12:09:45 +0900 Subject: [PATCH] Fix bug causing multiple instances of LogTape to import separate Logger instances --- CHANGES.md | 4 ++++ logtape/logger.ts | 16 ++++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 1c75c9c..93cb33c 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -8,6 +8,10 @@ Version 0.1.2 To be released. + - Fixed a bug where two or more versions of LogTape were imported in the same + runtime, the `Logger` instances would not be shared between them. This was + caused by the `Logger` instances being stored in a module-level variable. + Version 0.1.1 ------------- diff --git a/logtape/logger.ts b/logtape/logger.ts index 68995cc..d686017 100644 --- a/logtape/logger.ts +++ b/logtape/logger.ts @@ -356,9 +356,16 @@ export function getLogger(category: string | readonly string[] = []): Logger { } /** - * The root logger. + * The symbol for the global root logger. */ -let rootLogger: LoggerImpl | null = null; +const globalRootLoggerSymbol = Symbol.for("logtape.rootLogger"); + +/** + * The global root logger registry. + */ +interface GlobalRootLoggerRegistry { + [globalRootLoggerSymbol]?: LoggerImpl; +} /** * A logger implementation. Do not use this directly; use {@link getLogger} @@ -372,8 +379,13 @@ export class LoggerImpl implements Logger { readonly filters: Filter[]; static getLogger(category: string | readonly string[] = []): LoggerImpl { + let rootLogger: LoggerImpl | null = globalRootLoggerSymbol in globalThis + ? (globalThis as GlobalRootLoggerRegistry)[globalRootLoggerSymbol] ?? null + : null; if (rootLogger == null) { rootLogger = new LoggerImpl(null, []); + (globalThis as GlobalRootLoggerRegistry)[globalRootLoggerSymbol] = + rootLogger; } if (typeof category === "string") return rootLogger.getChild(category); if (category.length === 0) return rootLogger;