Skip to content

Commit

Permalink
feat(logger): allow passing censorship from instantiation
Browse files Browse the repository at this point in the history
  • Loading branch information
lowlighter committed Sep 29, 2024
1 parent ffe535e commit fa8e8ea
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
11 changes: 10 additions & 1 deletion logger/_logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
// deno-lint-ignore ban-types
export class Logger<T extends Record<PropertyKey, unknown> = {}> {
/** Constructor. */
constructor({ level, format, output, tags, ...options } = {} as LoggerOptions<T>) {
constructor({ level, format, output, tags, censor, ...options } = {} as LoggerOptions<T>) {
if (globalThis.Deno?.permissions.querySync?.({ name: "env", variable: "LOG_LEVEL" }).state === "granted") {
level ??= globalThis.Deno?.env.get("LOG_LEVEL") as LoggerOptions<T>["level"]
}
Expand All @@ -46,6 +46,9 @@ export class Logger<T extends Record<PropertyKey, unknown> = {}> {
this.#options = { date: false, time: false, delta: true, caller: { file: false, name: false, line: false, fileformat: null } }
this.level(level).format(format).options(options)
this.tags = (tags ?? {}) as Logger<T>["tags"]
if (censor) {
;[censor].flat().forEach((censor) => this.censor(censor))
}
}

/** Logger output streams. */
Expand Down Expand Up @@ -470,6 +473,12 @@ export type LoggerOptions<T extends Record<PropertyKey, unknown> = {}> = {
output?: Nullable<Record<"error" | "warn" | "info" | "log" | "debug", Function>>
/** Logger tags. */
tags?: T
/**
* Register censored values or keys.
*
* See {@link Logger.censor} for more information.
*/
censor?: Parameters<Logger["censor"]>[0] | Array<Parameters<Logger["censor"]>[0]>
/** Display caller informations (requires to be run on a V8 runtime). */
caller?: {
/** Display caller file path (e.g. `file://shadow/libs/logger/mod.ts`). */
Expand Down
2 changes: 1 addition & 1 deletion logger/_logger_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ test("deno")("`Logger.prototype.format.text()` formats delta value smartly", ()

test("deno")("`Logger.prototype.format.text()` supports censorship", () => {
const output = { log: fn(), debug: fn(), info: fn(), warn: fn(), error: fn() }
const log = new Logger({ output, level: "log", format: "text", tags: { token: "api_foobar" } })
const log = new Logger({ output, level: "log", format: "text", tags: { token: "api_foobar" }, censor: {} })
log
.censor({ values: [/(api_)\w+/], replace: "$1****" })
.censor({ keys: ["password", /^secret_/], replace: "****" })
Expand Down

0 comments on commit fa8e8ea

Please sign in to comment.