Skip to content

Commit 025b0ea

Browse files
committed
fix(logger): better handle of errors instances
1 parent 6e34628 commit 025b0ea

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

logger/_logger.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232
* @author Simon Lecoq (lowlighter)
3333
* @license MIT
3434
*/
35+
import { red } from "@std/fmt/colors"
36+
3537
// deno-lint-ignore ban-types
3638
export class Logger<T extends Record<PropertyKey, unknown> = {}> {
3739
/** Constructor. */
@@ -337,9 +339,16 @@ export class Logger<T extends Record<PropertyKey, unknown> = {}> {
337339
* Inspect a value.
338340
* When running on Deno, this method will use the `Deno.inspect` method.
339341
*/
340-
#inspect(value: unknown) {
342+
#inspect(value: unknown, { tag = false } = {}) {
341343
value = this.#censor(value)
342-
return typeof value === "string" ? value : globalThis.Deno?.inspect(value, { colors: true, depth: Infinity, strAbbreviateSize: Infinity }) ?? value
344+
switch (true) {
345+
case !tag && typeof value === "string":
346+
return value
347+
case value && value instanceof Error:
348+
return red(value.stack || value.message)
349+
default:
350+
return globalThis.Deno?.inspect(value, { colors: true, depth: Infinity, strAbbreviateSize: Infinity }) ?? value
351+
}
343352
}
344353

345354
/** Logger formatter. */
@@ -406,7 +415,7 @@ export class Logger<T extends Record<PropertyKey, unknown> = {}> {
406415
}
407416
const tags = []
408417
for (const [key, value] of Object.entries(logger.tags)) {
409-
tags.push(`${key}:${logger.#inspect(value)}`)
418+
tags.push(`${key}:${logger.#inspect(value, { tag: true })}`)
410419
}
411420
text.push(`%c ${tags.join(" ").trim()} %c`)
412421
styles.push(`background-color: black`, "")

logger/_logger_test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ if (runtime === "deno") {
222222
.censor({ values: [/(api_)\w+/], replace: "$1****" })
223223
.censor({ keys: ["password", /^secret_/], replace: "****" })
224224
.log("my key is <api_foobar>", { user: "foo", password: "bar", secret_a: "a", secret_b: "b", friend: "bar", meta: { created: 123, deleted: null, secret_c: "c", api: "<api_foobar>", fn() {} } })
225-
expect(text(output.log, { call: 0 }).header).toContain("token:api_****")
225+
expect(text(output.log, { call: 0 }).header).toContain('token:"api_****"')
226226
expect(text(output.log, { call: 0 }).content[0]).toContain("my key is <api_****>")
227227
expect(text(output.log, { call: 0 }).content[1]).toContain('user: "foo"')
228228
expect(text(output.log, { call: 0 }).content[1]).toContain('password: "****"')

0 commit comments

Comments
 (0)