File size: 6,012 Bytes
4e23b01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import { join } from 'node:path';

import { extractError, formatEntry, redactCtx } from './formatter';
import { RotatingFileSink } from './sinks';
import {
  type LogContext,
  type LogEntry,
  type LogLevel,
  type LogPayload,
  type Logger,
  type LoggingConfig,
  type RootLogger,
  levelEnabled,
} from './types';

const ROOT_SYMBOL = Symbol.for('kimi.logger.root');

class RootLoggerImpl implements RootLogger {
  private config: LoggingConfig | undefined;
  private globalSink: RotatingFileSink | undefined;

  isConfigured(): boolean {
    return this.config !== undefined;
  }

  getConfig(): LoggingConfig | undefined {
    return this.config;
  }

  configure(config: LoggingConfig): Promise<void> {
    if (this.config !== undefined && sameLoggingConfig(this.config, config)) {
      return Promise.resolve();
    }
    const oldGlobalSink = this.globalSink;
    this.config = config;
    this.globalSink = makeGlobalSink(config);
    return oldGlobalSink?.close() ?? Promise.resolve();
  }

  async flush(): Promise<boolean> {
    if (this.globalSink === undefined) return true;
    return this.globalSink.flush();
  }

  flushSync(): void {
    this.globalSink?.flushSync();
  }

  emit(entry: LogEntry): void {
    const config = this.config;
    if (config === undefined || config.level === 'off') return;
    if (!levelEnabled(config.level, entry.level)) return;
    const formatted = formatEntry(entry);
    if (formatted.dropped) return;
    this.globalSink?.enqueue(formatted.text + '\n');
  }

  async __shutdownForTest(): Promise<void> {
    const close = this.globalSink?.close();
    this.globalSink = undefined;
    this.config = undefined;
    await close;
  }
}

function getRootInternal(): RootLoggerImpl {
  const globalAny = globalThis as Record<symbol, unknown>;
  const existing = globalAny[ROOT_SYMBOL];
  if (existing instanceof RootLoggerImpl) return existing;
  const fresh = new RootLoggerImpl();
  globalAny[ROOT_SYMBOL] = fresh;
  return fresh;
}

export function getRootLogger(): RootLogger {
  return getRootInternal();
}

export function flushDiagnosticLogs(): Promise<boolean> {
  return getRootInternal().flush();
}

export function flushDiagnosticLogsSync(): void {
  getRootInternal().flushSync();
}

class LoggerImpl implements Logger {
  constructor(private readonly boundCtx: LogContext) {}

  error(message: string, payload?: LogPayload): void {
    this.emitAt('error', message, payload);
  }
  warn(message: string, payload?: LogPayload): void {
    this.emitAt('warn', message, payload);
  }
  info(message: string, payload?: LogPayload): void {
    this.emitAt('info', message, payload);
  }
  debug(message: string, payload?: LogPayload): void {
    this.emitAt('debug', message, payload);
  }

  createChild(ctx: LogContext): Logger {
    return new LoggerImpl({ ...this.boundCtx, ...ctx });
  }

  private emitAt(
    level: Exclude<LogLevel, 'off'>,
    message: string,
    payload: LogPayload,
  ): void {
    const root = getRootInternal();
    if (!root.isConfigured()) return;
    try {
      const { ctx: payloadCtx, error } = resolvePayload(payload);
      const ctx = mergeCtx(payloadCtx, this.boundCtx);
      root.emit({
        t: Date.now(),
        level,
        msg: message,
        ctx,
        error,
      });
    } catch {
    }
  }
}

function makeGlobalSink(config: LoggingConfig): RotatingFileSink | undefined {
  if (config.level === 'off') return undefined;
  return new RotatingFileSink({
    path: config.globalLogPath,
    maxBytes: config.globalMaxBytes,
    files: config.globalFiles,
  });
}

function sameLoggingConfig(a: LoggingConfig, b: LoggingConfig): boolean {
  return (
    a.level === b.level &&
    a.globalLogPath === b.globalLogPath &&
    a.globalMaxBytes === b.globalMaxBytes &&
    a.globalFiles === b.globalFiles &&
    a.sessionMaxBytes === b.sessionMaxBytes &&
    a.sessionFiles === b.sessionFiles
  );
}

function resolvePayload(
  payload: LogPayload,
): { ctx: LogContext | undefined; error: LogEntry['error'] } {
  if (payload === undefined || payload === null) {
    return { ctx: undefined, error: undefined };
  }
  if (payload instanceof Error) {
    return { ctx: undefined, error: extractError(payload) };
  }
  if (typeof payload === 'object') {
    const obj = payload as Record<string, unknown>;
    if (obj['error'] instanceof Error) {
      const { error: errValue, ...rest } = obj;
      return { ctx: rest as LogContext, error: extractError(errValue) };
    }
    return { ctx: obj as LogContext, error: undefined };
  }
  if (
    typeof payload === 'string' ||
    typeof payload === 'number' ||
    typeof payload === 'boolean' ||
    typeof payload === 'bigint' ||
    typeof payload === 'symbol'
  ) {
    return { ctx: { reason: String(payload) }, error: undefined };
  }
  if (typeof payload === 'function') {
    const reason = payload.name === '' ? '[Function]' : `[Function: ${payload.name}]`;
    return { ctx: { reason }, error: undefined };
  }
  return { ctx: { reason: Object.prototype.toString.call(payload) }, error: undefined };
}

function mergeCtx(
  payloadCtx: LogContext | undefined,
  boundCtx: LogContext,
): LogContext | undefined {
  const boundHasKeys = Object.keys(boundCtx).length > 0;
  if (!boundHasKeys) return payloadCtx;
  if (payloadCtx === undefined) return { ...boundCtx };
  return { ...payloadCtx, ...boundCtx };
}

export const log: Logger = new LoggerImpl({});

export function redact<T>(value: T): T {
  if (value === null || typeof value !== 'object') return value;
  return redactCtx({ value: value as unknown })['value'] as T;
}

export async function __resetRootLoggerForTest(): Promise<void> {
  const globalAny = globalThis as Record<symbol, unknown>;
  const existing = globalAny[ROOT_SYMBOL];
  if (existing instanceof RootLoggerImpl) {
    await existing.__shutdownForTest();
  }
  globalAny[ROOT_SYMBOL] = undefined;
}

export function resolveGlobalLogPath(homeDir: string): string {
  return join(homeDir, 'logs', 'kimi-code.log');
}