All files / log / formatters.ts

100.00% Branches 3/3
100.00% Lines 16/16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x18
x25
x25
x25
x25
x25
x25
x25
 
x25
x25
x27
x25
x33
x33
x25
 
 
x54
















































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.
import type { LogRecord } from "./logger.ts";

/**
 * JSON log formatter.
 *
 * @example Usage
 * ```ts
 * import { LogRecord } from "@std/log/logger";
 * import { jsonFormatter } from "@std/log/formatters";
 * import { LogLevels } from "@std/log/levels";
 * import { assertEquals } from "@std/assert/equals";
 *
 * const record = new LogRecord({
 *   msg: "Hello, world!",
 *   args: ["foo", "bar"],
 *   level: LogLevels.INFO,
 *   loggerName: "example",
 * });
 * const formatted = jsonFormatter(record);
 *
 * assertEquals(
 *   formatted,
 *   `{"level":"INFO","datetime":${record.datetime.getTime()},"message":"Hello, world!","args":["foo","bar"]}`,
 * );
 * ```
 *
 * @param logRecord Log record to format.
 * @returns JSON string representation of the log record.
 */
export function jsonFormatter(logRecord: LogRecord): string {
  return JSON.stringify({
    level: logRecord.levelName,
    datetime: logRecord.datetime.getTime(),
    message: logRecord.msg,
    args: flattenArgs(logRecord.args),
  });
}

function flattenArgs(args: unknown[]): unknown {
  if (args.length === 1) {
    return args[0];
  } else if (args.length > 1) {
    return args;
  }
}

/** Formatters for log records. */
export const formatters = { jsonFormatter } as const;