src.nth.io/

summaryrefslogtreecommitdiff
path: root/src/logging.ts
blob: e7b26f20aadd15094fe826684260fec80d61d617 (plain)
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
 * Structured, level-filtered logging for the service's own messages.
 *
 * matter.js library logging is configured separately (see controller.ts); this
 * logger covers service-level events in the format:
 *
 *   2026-07-26T20:00:00.100Z INFO  controller Connected to Matter node 1
 */

export const LOG_LEVELS = ["debug", "info", "warn", "error"] as const;
export type LogLevel = (typeof LOG_LEVELS)[number];

export function isLogLevel(value: unknown): value is LogLevel {
  return typeof value === "string" && (LOG_LEVELS as readonly string[]).includes(value);
}

const LEVEL_RANK: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3 };
const LEVEL_LABEL: Record<LogLevel, string> = {
  debug: "DEBUG",
  info: "INFO ",
  warn: "WARN ",
  error: "ERROR",
};

let globalLevel: LogLevel = "info";

export function setLogLevel(level: LogLevel): void {
  globalLevel = level;
}

export function getLogLevel(): LogLevel {
  return globalLevel;
}

function write(level: LogLevel, module: string, message: string): void {
  if (LEVEL_RANK[level] < LEVEL_RANK[globalLevel]) return;
  const line = `${new Date().toISOString()} ${LEVEL_LABEL[level]} ${module} ${message}`;
  // All log levels go to stderr: stdout is reserved for command output so
  // that --json (and any piped human output) is never interleaved with logs.
  process.stderr.write(line + "\n");
}

/** A logger bound to a module name (e.g. "controller", "sync"). */
export class Log {
  constructor(private readonly module: string) {}

  debug(message: string): void {
    write("debug", this.module, message);
  }

  info(message: string): void {
    write("info", this.module, message);
  }

  warn(message: string): void {
    write("warn", this.module, message);
  }

  error(message: string, cause?: unknown): void {
    write("error", this.module, cause === undefined ? message : `${message}: ${describeError(cause)}`);
  }
}

export function describeError(cause: unknown): string {
  if (cause instanceof Error) {
    return cause.message;
  }
  return String(cause);
}