All files / src/server/platform log-context.server.ts

100% Statements 6/6
100% Branches 4/4
100% Functions 3/3
100% Lines 6/6

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            25x       18x         37x 37x 5x         673x    
// Fields every log line of the current request carries, without passing them
// around: the trace id from the start, the user id once the session is known.
// AsyncLocalStorage follows the request through every await.
import { AsyncLocalStorage } from 'node:async_hooks'
import type { LogFields } from '#/server/log/log'
 
const storage = new AsyncLocalStorage<LogFields>()
 
/** Runs `fn` with its own log context, starting from `fields`. */
export function runWithLogContext<T>(fields: LogFields, fn: () => T): T {
  return storage.run({ ...fields }, fn)
}
 
/** Adds fields to the current request's log context, e.g. `userId`. */
export function addLogContext(fields: LogFields): void {
  const current = storage.getStore()
  if (current) {
    Object.assign(current, fields)
  }
}
 
export function currentLogContext(): LogFields {
  return storage.getStore() ?? {}
}