api/src/lib/log.ts

47 lines · 1785 bytes

9 symbols in this file
 1/**
 2 * Structured logger util used everywhere in the API
 3 * When running in TTY or dev, you get pretty output
 4 * In prod it's structured JSON for log aggregation
 5 */
 6
 7/* eslint-disable no-console */
 8
 9type Level = 'info' | 'warn' | 'error'
10
11const colour: Record<Level, string> = {
12  info: '\x1b[36m',
13  warn: '\x1b[33m',
14  error: '\x1b[31m',
15}
16const dim = '\x1b[2m'
17const reset = '\x1b[0m'
18
19// Detect if running in a real terminal. Will be false for Workers/Docker
20const isTty = typeof process !== 'undefined' && Boolean(process.stdout?.isTTY)
21
22// Coloured single-line format for local dev terminals
23const pretty = (level: Level, msg: string, meta?: Record<string, unknown>) => {
24  const time = new Date().toISOString().slice(11, 19)
25  const tag = `${colour[level]}${level.toUpperCase().padEnd(5)}${reset}`
26  const extra =
27    meta && Object.keys(meta).length ? ` ${dim}${JSON.stringify(meta)}${reset}` : ''
28  return `${dim}${time}${reset} ${tag} ${msg}${extra}`
29}
30
31// JSON line for log aggregators, Docker stdout, Workers tail
32const json = (level: Level, msg: string, meta?: Record<string, unknown>) =>
33  JSON.stringify({ t: new Date().toISOString(), level, msg, ...meta })
34
35const emit = (level: Level, msg: string, meta?: Record<string, unknown>) => {
36  const line = isTty ? pretty(level, msg, meta) : json(level, msg, meta)
37  if (level === 'error') console.error(line)
38  else if (level === 'warn') console.warn(line)
39  else console.log(line)
40}
41
42// Main logger. Used like: `log.info('hello', { something: 123 })`
43export const log = {
44  info: (msg: string, meta?: Record<string, unknown>) => emit('info', msg, meta),
45  warn: (msg: string, meta?: Record<string, unknown>) => emit('warn', msg, meta),
46  error: (msg: string, meta?: Record<string, unknown>) => emit('error', msg, meta),
47}