im-logger.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import type { Logger as PinoLogger } from 'pino';
  2. import {
  3. createDiskLogTransport,
  4. createStructuredLogger,
  5. wrapTraceContextLogger,
  6. type DiskLogTransport,
  7. type DiskLogTransportOptions,
  8. type StructuredLoggerOptions,
  9. type TraceContextLike,
  10. } from '../logging/index.js';
  11. import type { LocalRuntimeLogger, LogFields } from './logger.js';
  12. /**
  13. * IM-subsystem logger facade.
  14. *
  15. * Mirror of `common/logger.ts` but with a physically independent pino
  16. * instance and disk transport so the AC audit line + all IM channel/adapter
  17. * chatter lands in `<dataDir>/v2/observability/logs/im-runtime-<YYYYMMDDHH>[.N].log`
  18. * — separate from the main `runtime-*.log` so operators can grep it, retain
  19. * it, and rotate it independently.
  20. *
  21. * Allowed APIs: `info`, `warn`, `error`, plus the `ctxInfo`/`ctxWarn`/`ctxError`
  22. * exports (re-exported through `common/index.ts` as `imCtxInfo` / `imCtxWarn`
  23. * / `imCtxError`). Business code (IM channels, adapters, permission-bridge,
  24. * host-channels wiring) imports `imLogger` from this module aliased as
  25. * `logger`; the AC store consumes it through the `bindAccessControlAuditLogger`
  26. * adapter in `channels/access-control-store.ts`.
  27. *
  28. * Persistent-disk fan-out is opt-in via {@link configureImLogger} — the host
  29. * wiring (Electron main, CLI `tui.ts`) calls it during boot with a `dir`,
  30. * which swaps the module-level base logger for one whose pretty output is
  31. * teed into the `im-runtime-` file family. Electron's feedback upload path
  32. * scans that prefix (see `apps/electron/main/utils/extra-log-source.ts`), so
  33. * user diagnostic bundles automatically include IM audit history.
  34. */
  35. let activeDisk: DiskLogTransport | null = null;
  36. let baseLogger: PinoLogger = wrapTraceContextLogger(createStructuredLogger());
  37. /**
  38. * Options for {@link configureImLogger}. Shape mirrors
  39. * `ConfigureLocalRuntimeLoggingOptions` — the on-disk `prefix` is hard-coded
  40. * to `im-runtime` so callers cannot accidentally point IM logs at the main
  41. * `runtime-*.log` file family (that would defeat the whole point of the
  42. * split).
  43. */
  44. export interface ConfigureImLoggerOptions extends Omit<DiskLogTransportOptions, 'dir' | 'prefix'> {
  45. /**
  46. * Absolute path of the log directory. Same shape as
  47. * `configureLocalRuntimeLogging` so the host can point both loggers at
  48. * the same v2 logs dir; only the on-disk prefix distinguishes IM
  49. * (`im-runtime-`) from main runtime (`runtime-`). When omitted, disk
  50. * fan-out is disabled and imLogger writes to stdout only.
  51. */
  52. dir?: string;
  53. /** Overrides for the pino logger factory. Rarely used outside tests. */
  54. loggerOptions?: Omit<StructuredLoggerOptions, 'disk'>;
  55. }
  56. /**
  57. * Install (or re-install) the IM-subsystem engineering logger. Idempotent:
  58. * the previous disk transport (if any) is detached synchronously and its
  59. * final flush runs in the background.
  60. *
  61. * When `opts.dir` is omitted the disk arm is disabled and the base logger
  62. * falls back to stdout-only — the pre-configure default. That path is
  63. * intended for tests / early boot before dataDir is resolved.
  64. */
  65. export function configureImLogger(opts: ConfigureImLoggerOptions = {}): void {
  66. const previous = activeDisk;
  67. activeDisk = null;
  68. if (opts.dir) {
  69. const { dir, maxBytesPerFile, maxTotalBytes, retentionMs, now, onError, loggerOptions } = opts;
  70. // prefix: 'im-runtime' — disk transport composes '<prefix>-<hourKey>.log',
  71. // i.e. 'im-runtime-2026061209.log'. Never pass 'im-runtime-' here or the
  72. // transport would produce a double-dashed 'im-runtime--<hour>.log'.
  73. const diskOpts: DiskLogTransportOptions = { dir, prefix: 'im-runtime' };
  74. if (maxBytesPerFile !== undefined) diskOpts.maxBytesPerFile = maxBytesPerFile;
  75. if (maxTotalBytes !== undefined) diskOpts.maxTotalBytes = maxTotalBytes;
  76. if (retentionMs !== undefined) diskOpts.retentionMs = retentionMs;
  77. if (now !== undefined) diskOpts.now = now;
  78. if (onError !== undefined) diskOpts.onError = onError;
  79. const disk = createDiskLogTransport(diskOpts);
  80. activeDisk = disk;
  81. baseLogger = wrapTraceContextLogger(createStructuredLogger({ ...loggerOptions, disk }));
  82. } else {
  83. baseLogger = wrapTraceContextLogger(createStructuredLogger(opts.loggerOptions ?? {}));
  84. }
  85. if (previous) {
  86. // Fire-and-forget: the previous transport keeps draining its own write
  87. // chain in the background. Any close errors were already routed through
  88. // its `onError` sink; we just prevent an unhandled rejection.
  89. void previous.close().catch(() => {});
  90. }
  91. }
  92. /**
  93. * Flush pending disk writes without tearing down the base logger. Called
  94. * by the feedback upload path before it reads the log directory.
  95. */
  96. export async function flushImLogger(): Promise<void> {
  97. if (!activeDisk) return;
  98. await activeDisk.flush();
  99. }
  100. /**
  101. * Close the disk transport (flush + retention sweep + stop accepting new
  102. * writes). Called during Electron `will-quit` / CLI graceful shutdown so
  103. * the final rotation sweep runs before the process exits.
  104. *
  105. * After shutdown the module-level logger keeps working (stdout only) — a
  106. * subsequent {@link configureImLogger} call re-installs it.
  107. */
  108. export async function shutdownImLogger(): Promise<void> {
  109. if (!activeDisk) return;
  110. const old = activeDisk;
  111. activeDisk = null;
  112. try {
  113. await old.close();
  114. } catch {
  115. // Already surfaced via onError.
  116. }
  117. baseLogger = wrapTraceContextLogger(createStructuredLogger());
  118. }
  119. export const imLogger: LocalRuntimeLogger = {
  120. info(fields: LogFields, message: string): void {
  121. baseLogger.info(fields, message);
  122. },
  123. warn(fields: LogFields, message: string): void {
  124. baseLogger.warn(fields, message);
  125. },
  126. error(fields: LogFields, message: string): void {
  127. baseLogger.error(fields, message);
  128. },
  129. ctxInfo(ctx: TraceContextLike, fields: LogFields, message: string): void {
  130. baseLogger.info({ ctx, ...fields }, message);
  131. },
  132. ctxWarn(ctx: TraceContextLike, fields: LogFields, message: string): void {
  133. baseLogger.warn({ ctx, ...fields }, message);
  134. },
  135. ctxError(ctx: TraceContextLike, fields: LogFields, message: string): void {
  136. baseLogger.error({ ctx, ...fields }, message);
  137. },
  138. };
  139. export function ctxInfo(ctx: TraceContextLike, fields: LogFields, message: string): void {
  140. baseLogger.info({ ctx, ...fields }, message);
  141. }
  142. export function ctxWarn(ctx: TraceContextLike, fields: LogFields, message: string): void {
  143. baseLogger.warn({ ctx, ...fields }, message);
  144. }
  145. export function ctxError(ctx: TraceContextLike, fields: LogFields, message: string): void {
  146. baseLogger.error({ ctx, ...fields }, message);
  147. }
  148. /**
  149. * Test-only helper mirroring `common/logger.ts`'s `__getBaseLoggerForTests`.
  150. * The 4 IM tests that previously spied on the main logger's baseLogger now
  151. * spy this one instead; shape and behaviour are identical.
  152. *
  153. * @internal
  154. */
  155. export function __getBaseLoggerForTests(): PinoLogger {
  156. return baseLogger;
  157. }
  158. /**
  159. * Test-only helper: returns the active disk transport so spec files can
  160. * inspect rotation state / flush during assertions.
  161. *
  162. * @internal
  163. */
  164. export function __getActiveDiskTransportForTests(): DiskLogTransport | null {
  165. return activeDisk;
  166. }