All files / shared-utils/src log.ts

100% Statements 39/39
100% Branches 12/12
100% Functions 16/16
100% Lines 36/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                        10x 10x 10x                                 7x         7x 7x       7x       17x   24x         7x   7x 1x     7x   15x 2x   13x                 8x 1x   7x 7x 1x   6x 6x 6x 1x 1x   5x     5x 5x 5x 1x 1x   4x               5x 1x 1x      
import pino from 'pino';
 
// Lazy-load Node built-ins so the module remains importable from a browser bundle (the file logger is the only
// caller that needs them, and the browser side never invokes `createFileLogger`). Vite externalises these
// `node:` prefixes for browser targets but only emits a runtime error if code actually reaches them — keeping
// the resolution lazy confines the error to the Node-only `createFileLogger` path that browsers never call.
type NodeFS = typeof import('node:fs');
type NodeFSPromises = typeof import('node:fs/promises');
type NodePath = typeof import('node:path');
let nodeFSPromise: Promise<NodeFS> | undefined;
let nodeFSPromisesPromise: Promise<NodeFSPromises> | undefined;
let nodePathPromise: Promise<NodePath> | undefined;
const loadNodeFS = (): Promise<NodeFS> => (nodeFSPromise ??= import('node:fs'));
const loadNodeFSPromises = (): Promise<NodeFSPromises> => (nodeFSPromisesPromise ??= import('node:fs/promises'));
const loadNodePath = (): Promise<NodePath> => (nodePathPromise ??= import('node:path'));
 
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
 
export interface LogEntry {
  source: string;
  level: LogLevel;
  event: string;
  fields?: Record<string, unknown>;
}
 
export interface Logger {
  log: (entry: LogEntry) => void;
  close: () => Promise<void>;
}
 
export async function createFileLogger(logFilePath: string): Promise<Logger> {
  const [{ mkdir }, { dirname }, { createWriteStream }] = await Promise.all([
    loadNodeFSPromises(),
    loadNodePath(),
    loadNodeFS(),
  ]);
  await mkdir(dirname(logFilePath), { recursive: true });
  const stream = createWriteStream(logFilePath, {
    flags: 'a',
    encoding: 'utf8',
  });
  const logger = pino(
    {
      base: { pid: process.pid },
      messageKey: 'event',
      timestamp: () => `,"ts":"${new Date().toISOString()}"`,
      formatters: {
        level: (label) => ({ level: label }),
      },
    },
    stream,
  );
  let closed = false;
  let streamError: Error | undefined;
  stream.on('error', (error) => {
    streamError = error;
  });
 
  return {
    log: (entry) => {
      if (closed || streamError) {
        return;
      }
      logger[entry.level](
        {
          source: entry.source,
          fields: entry.fields,
        },
        entry.event,
      );
    },
    close: async () => {
      if (closed) {
        return;
      }
      closed = true;
      if (streamError) {
        throw streamError;
      }
      await new Promise<void>((resolve, reject) => {
        logger.flush((error) => {
          if (error) {
            reject(error);
            return;
          }
          resolve();
        });
      });
      await new Promise<void>((resolve, reject) => {
        stream.end((error?: Error | null) => {
          if (error) {
            reject(error);
            return;
          }
          resolve();
        });
      });
    },
  };
}
 
export function createNoopLogger(): Logger {
  return {
    log: () => undefined,
    close: () => Promise.resolve(),
  };
}