From 9e70de81eacc3f1124f1f61f590838188e700d0e Mon Sep 17 00:00:00 2001 From: DmitryL Date: Wed, 9 Oct 2024 17:20:43 +0300 Subject: [PATCH] Allow category deep nesting --- logtape/category.ts | 15 +++++++++++++-- logtape/logger.test.ts | 4 ++++ logtape/logger.ts | 14 +++++++++----- 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/logtape/category.ts b/logtape/category.ts index 940c499..1270f50 100644 --- a/logtape/category.ts +++ b/logtape/category.ts @@ -1,3 +1,14 @@ -export type CategoryList = Readonly; +export type CategoryList = readonly string[]; -export type Category = string | CategoryList; +export type Category = string | readonly Category[]; + +export function getCategoryList(category: Category): CategoryList { + return deepFlatten(category); +} + +function deepFlatten(arr: Category): string[] { + if (typeof arr === "string") return [arr]; + return arr.flatMap((item) => ( + typeof item === "string" ? [item] : deepFlatten(item) + )); +} diff --git a/logtape/logger.test.ts b/logtape/logger.test.ts index 6b31624..60dd205 100644 --- a/logtape/logger.test.ts +++ b/logtape/logger.test.ts @@ -37,6 +37,10 @@ Deno.test("getLogger()", () => { getLogger(["foo", "bar"]), getLogger().getChild("foo").getChild("bar"), ); + assertStrictEquals( + getLogger(["foo", ["bar", ["baz", ["qux"]]]]), + getLogger().getChild("foo").getChild("bar").getChild("baz").getChild("qux"), + ); }); Deno.test("Logger.getChild()", () => { diff --git a/logtape/logger.ts b/logtape/logger.ts index 6e496ee..0ba4362 100644 --- a/logtape/logger.ts +++ b/logtape/logger.ts @@ -1,4 +1,8 @@ -import type { Category, CategoryList } from "./category.ts"; +import { + type Category, + type CategoryList, + getCategoryList, +} from "./category.ts"; import type { Filter } from "./filter.ts"; import type { LogLevel } from "./level.ts"; import type { LogRecord } from "./record.ts"; @@ -422,7 +426,6 @@ export class LoggerImpl implements Logger { (globalThis as GlobalRootLoggerRegistry)[globalRootLoggerSymbol] = rootLogger; } - if (typeof category === "string") return rootLogger.getChild(category); if (category.length === 0) return rootLogger; return rootLogger.getChild(category); } @@ -438,7 +441,8 @@ export class LoggerImpl implements Logger { getChild( subcategory: Category, ): LoggerImpl { - const name = typeof subcategory === "string" ? subcategory : subcategory[0]; + const subcategoryList = getCategoryList(subcategory); + const name = subcategoryList[0]; const childRef = this.children[name]; let child: LoggerImpl | undefined = childRef instanceof LoggerImpl ? childRef @@ -449,10 +453,10 @@ export class LoggerImpl implements Logger { ? new WeakRef(child) : child; } - if (typeof subcategory === "string" || subcategory.length === 1) { + if (subcategoryList.length === 1) { return child; } - return child.getChild(subcategory.slice(1)); + return child.getChild(subcategoryList.slice(1)); } /**