Skip to content
Logixlysia
Esc
↑↓navigate↵open⌘Jpreview
On this page

Request context

Accumulate request-scoped fields into a single access log line

Logixlysia can accumulate context during a request and merge it into the automatic access log, without replacing your existing logger.info() API.

Basic usage

import { Elysia } from 'elysia'
import logixlysia from 'logixlysia'

const app = new Elysia()
  .use(logixlysia())
  .get('/checkout', ({ request, store }) => {
    store.logger.mergeContext(request, { userId: 'usr_123' })
    store.logger.mergeContext(request, { cartTotal: 9999 })
    return { ok: true }
  })

The final INFO access log includes a context object with userId and cartTotal (and renders as a context tree when showContextTree is enabled).

A custom log (log.info, store.logger.info(request, …), useLogger().info) is a line of its own. It is written when you call it, before the response exists, so it carries no status and its durationMs is the time elapsed so far. The access line still follows with the request’s status, its full durationMs and the response-phase enricher fields. To add fields to the access line without writing another line, use mergeContext.

Precedence

When you call logger.info(request, message, { ...explicit }), keys in the explicit context override accumulated values. Non-colliding keys from both sources are kept.

Nested objects

Plain objects merge key by key, so each layer of your app can add to a nested field without knowing what earlier layers wrote:

app.get('/seat', ({ log }) => {
  log.mergeContext({ user: { id: 'usr_123' } })
  log.mergeContext({ user: { plan: 'pro' } })
  log.info('seated', { user: { seat: 2 } })
  return { ok: true }
})

That custom line logs user as { id: 'usr_123', plan: 'pro', seat: 2 }. seat is per-line context, so it is not kept for later lines. The same rule applies to explicit context passed to logger.info(request, message, { ...explicit }).

Value Behaviour
Plain and null-prototype objects on both sides Merged into a fresh object. The objects you passed are never changed.
Arrays, Date, class instances, null and primitives Replace the earlier value.
A nested __proto__ or constructor key Kept as an ordinary key. Object.prototype is never touched.
Objects nested deeper than 8 levels, including cycles Replace instead of merging, so a cyclic object cannot overflow the stack.

To replace a whole nested object, send null or an array. A typed field’s type has to allow that value, for example user: { id: string } | null. Merging is also why a nested field in a typed context only needs the keys you are setting.

Reading context

const ctx = store.logger.getContext(request)

Request-Scoped Logger & AsyncLocalStorage

Instead of manually passing the request object to store.logger methods (e.g. store.logger.info(request, message)), you can enable AsyncLocalStorage propagation:

logixlysia({
  config: {
    useAsyncLocalStorage: true
  }
})

The request-scoped logger log is always available on the Elysia handler context. Enabling useAsyncLocalStorage also lets useLogger() return the current request’s logger from nested service layers and helper functions.

useLogger() stays scoped to its request for the request’s whole life: in hooks registered after the plugin, inside a generator (streaming) handler’s body, in a handler that awaits app.handle() for another route, and in work that outlives the response. Outside a request it is a no-op. With aot: false, or with the plugin mounted inside group() or guard(), the plugin’s hooks keep the previous behaviour instead: the scope ends when they write the line, so hooks registered after the plugin get the no-op logger.

1. Handler Context (log)

Destructure log directly in your route handlers:

app.get('/user/:id', ({ log, params }) => {
  log.mergeContext({ userId: params.id })
  log.info('Fetched user profile')
  return { success: true }
})

This handler logs two lines. The custom one comes first and shows - where the status goes, because the response does not exist yet. The access line follows with the status the client got.

log.error also takes whatever you caught. A non-string is serialized like a thrown error, with its name, HttpError fields and cause:

declare function charge(): Promise<void>

app.post('/pay', async ({ log }) => {
  try {
    await charge()
  } catch (err) {
    log.error(err, { step: 'payment' })
    return { success: false }
  }
  return { success: true }
})

The line carries no status, because the handler may recover and respond with a 200.

A plain object, thrown or passed to log.error, is logged with its own fields. Its message field is the line’s message when it is a string; otherwise the message is Non-Error object. Prefer HttpError: with aot: true Elysia sends a thrown plain object to the client as the JSON body, every field included.

2. Global Hook (useLogger())

Import useLogger() to log or merge context from deeply nested operations without prop-drilling the request context:

import { useLogger } from 'logixlysia'

async function findUser(id: string) {
  const log = useLogger()
  log.mergeContext({ action: 'db_query' })
  log.info('Executing database lookup...')

  // Database lookup logic...
  return { id, name: 'John Doe' }
}

Typed Fields

userId on one route and user_id on the next is the kind of drift that makes a dashboard query quietly incomplete. Pass a field type to the plugin and TypeScript catches it at compile time:

import { Elysia } from 'elysia'
import logixlysia from 'logixlysia'

interface CheckoutFields {
  cartId: string
  itemCount: number
  userId: string
}

const app = new Elysia()
  .use(logixlysia<CheckoutFields>())
  .post('/pay', ({ log }) => {
    log.mergeContext({ userId: 'usr_123' }) // ✓
    log.info('charged', { itemCount: 3 }) // ✓

    log.mergeContext({ user_id: 'usr_123' }) // ✗ not in CheckoutFields
    log.mergeContext({ itemCount: 'three' }) // ✗ wrong type
    return { ok: true }
  })

Every field stays optional — you declare the vocabulary, not a requirement to fill it in on every route.

useLogger() takes the same parameter, so context stays typed outside the handler too:

import { useLogger } from 'logixlysia'

const chargeCard = async (amount: number) => {
  const log = useLogger<CheckoutFields>()
  log.mergeContext({ cartId: 'cart_9' })
}

This is type-only: there is no runtime cost, and leaving the parameter off keeps every key allowed, exactly as before.

useLogger() returns a request-scoped logger only with useAsyncLocalStorage: true; without it, it returns a logger that writes nothing. The first such call prints one warning to stderr naming the option, outside production only.

Was this page helpful?