All files / src/server/platform logger.server.ts

96.96% Statements 32/33
95.65% Branches 22/23
100% Functions 12/12
96.87% Lines 31/32

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 109 110 111 112                                          25x     9x     25x 6x 6x 3x 3x 2x 1x     1x                               743x 743x 743x 743x   743x 661x 1x   660x 1x           659x 659x 1764x   659x               743x   1x     608x     36x     16x                   727x 727x       647x          
// The Logger behind the request context (src/server/log/log.ts): one JSON
// object per line through console, which Workers Logs indexes field by field.
// The console method sets the level Workers Logs shows.
import {
  errorFields,
  isLogEvent,
  type LogEvent,
  type LogFields,
  type LogLevel,
  type Logger,
} from '#/server/log/log'
import { currentLogContext } from './log-context.server'
 
export interface LogLine extends LogFields {
  level: LogLevel
  event: LogEvent
  time: string
}
 
type Write = (level: LogLevel, line: LogLine) => void
 
const LEVELS: readonly LogLevel[] = ['debug', 'info', 'warn', 'error']
 
export function isLogLevel(value: unknown): value is LogLevel {
  return LEVELS.includes(value as LogLevel)
}
 
const writeToConsole: Write = (level, line) => {
  const json = JSON.stringify(line)
  if (level === 'error') {
    console.error(json)
  } else if (level === 'warn') {
    console.warn(json)
  } else Iif (level === 'debug') {
    console.debug(json)
  } else {
    console.log(json)
  }
}
 
export function createLogger(
  options: {
    /** Fields on every line, e.g. the Worker version. */
    base?: LogFields
    /** The current request's fields (trace id, user id). */
    context?: () => LogFields
    /** Lines below this level are dropped; LOG_LEVEL in wrangler.jsonc. */
    minLevel?: LogLevel
    write?: Write
    now?: () => Date
  } = {},
): Logger {
  const write = options.write ?? writeToConsole
  const now = options.now ?? (() => new Date())
  const context = options.context ?? currentLogContext
  const threshold = LEVELS.indexOf(options.minLevel ?? 'debug')
 
  const log = (level: LogLevel, event: LogEvent, fields: LogFields = {}) => {
    if (LEVELS.indexOf(level) < threshold) {
      return
    }
    if (!isLogEvent(event)) {
      throw new Error(
        `Log event "${String(event)}" is not <capability>.<event>`,
      )
    }
    // The version and the request's context (trace, user) win over the
    // call's fields, so no caller, nor a browser via /api/log, can forge them.
    const all = { ...fields, ...context(), ...options.base }
    const defined = Object.entries(all).filter(
      ([, value]) => value !== undefined,
    )
    write(level, {
      ...Object.fromEntries(defined),
      level,
      event,
      time: now().toISOString(),
    })
  }
 
  return {
    debug: (event, fields) => {
      log('debug', event, fields)
    },
    info: (event, fields) => {
      log('info', event, fields)
    },
    warn: (event, fields) => {
      log('warn', event, fields)
    },
    error: (event, fields = {}, error) => {
      log('error', event, {
        ...fields,
        ...(error === undefined ? {} : errorFields(error)),
      })
    },
  }
}
 
/** For tests: a logger that keeps its lines instead of printing them. */
export function createCaptureLogger(): { log: Logger; lines: LogLine[] } {
  const lines: LogLine[] = []
  return {
    lines,
    log: createLogger({
      write: (_level, line) => {
        lines.push(line)
      },
    }),
  }
}