Skip to content

Commit

Permalink
Allow category deep nesting
Browse files Browse the repository at this point in the history
  • Loading branch information
KROT47 committed Oct 9, 2024
1 parent dafe3a9 commit 9e70de8
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 7 deletions.
15 changes: 13 additions & 2 deletions logtape/category.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
export type CategoryList = Readonly<string[]>;
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)
));
}
4 changes: 4 additions & 0 deletions logtape/logger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()", () => {
Expand Down
14 changes: 9 additions & 5 deletions logtape/logger.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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);
}
Expand All @@ -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
Expand All @@ -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));
}

/**
Expand Down

0 comments on commit 9e70de8

Please sign in to comment.