File size: 2,362 Bytes
cd8bd0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
75
/**
 * Structured logger for the OmniRoute plugin.
 *
 * Levels: error < warn < info < debug
 * Default: warn (matches current console.warn behavior)
 * Set via features.logLevel in plugin options.
 */

export type LogLevel = "error" | "warn" | "info" | "debug";

const LEVEL_ORDER: Record<LogLevel, number> = {
  error: 0,
  warn: 1,
  info: 2,
  debug: 3,
};

const TAG = "[omniroute-plugin]";

function shouldLog(current: LogLevel, target: LogLevel): boolean {
  return LEVEL_ORDER[current] >= LEVEL_ORDER[target];
}

let _level: LogLevel = "warn";

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

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

function fmt(level: LogLevel, msg: string, tag?: string): string {
  const prefix = tag ? `${TAG}${tag}` : TAG;
  return `${prefix} [${level.toUpperCase()}] ${msg}`;
}

export const logger = {
  error(msg: string, ...args: unknown[]): void {
    if (shouldLog(_level, "error")) console.error(fmt("error", msg), ...args);
  },
  warn(msg: string, ...args: unknown[]): void {
    if (shouldLog(_level, "warn")) console.warn(fmt("warn", msg), ...args);
  },
  info(msg: string, ...args: unknown[]): void {
    if (shouldLog(_level, "info")) console.warn(fmt("info", msg), ...args);
  },
  debug(msg: string, ...args: unknown[]): void {
    if (shouldLog(_level, "debug")) console.warn(fmt("debug", msg), ...args);
  },
  /** Always emit regardless of level (for critical init breadcrumbs). */
  always(msg: string, ...args: unknown[]): void {
    console.warn(TAG, msg, ...args);
  },

  // ── Tagged child loggers ──────────────────────────────────────────────
  child(tag: string) {
    return {
      error: (msg: string, ...args: unknown[]) =>
        shouldLog(_level, "error") &&
        console.error(fmt("error", msg, tag), ...args),
      warn: (msg: string, ...args: unknown[]) =>
        shouldLog(_level, "warn") &&
        console.warn(fmt("warn", msg, tag), ...args),
      info: (msg: string, ...args: unknown[]) =>
        shouldLog(_level, "info") &&
        console.warn(fmt("info", msg, tag), ...args),
      debug: (msg: string, ...args: unknown[]) =>
        shouldLog(_level, "debug") &&
        console.warn(fmt("debug", msg, tag), ...args),
    };
  },
};