Logging
Structured logging on Cloudflare Workers with the @kit/shared logger: entry shape, levels, child loggers and what never to log.
Log with logger from @kit/shared/logger. Each call writes one structured object to the console, and Cloudflare Workers Logs indexes it field by field, so you can filter on userId or route in the dashboard instead of grepping strings. There is no vendor, no async setup and no getLogger(): import it and call it.
import { logger } from '@kit/shared/logger';logger.info({ userId: user.id, plan: 'pro' }, 'Subscription upgraded');logger.warn('Webhook retried');Entry Shape
Every call writes this object:
{ ...bindings, ...fields, level, message }bindingscome fromchild()(see below).fieldsis the object you pass first. It is optional:logger.info('message')works too.levelandmessageare written last, so a field namedlevelormessagecan't override them.
The logger never throws. A value it can't read becomes '[unserializable]', nesting deeper than 10 levels becomes '[max depth]', and an Error keeps its message, stack, cause and own properties. One bad field never loses the rest of the entry, and a logging failure never breaks the request.
Levels
| Call | Console method | Workers Logs level |
|---|---|---|
logger.debug(...) | console.debug | debug |
logger.info(...) | console.info | info |
logger.warn(...) | console.warn | warn |
logger.error(...) | console.error | error |
There is no fatal: use error. Workers Logs records the console method as the entry's level, so your logger.error entries show up when you filter on errors, next to uncaught exceptions and console.error calls from other code.
Child Loggers
child(bindings) returns a logger that adds bindings to every entry. Use it to tag everything a module or handler writes:
import { defineHandler } from 'void';import { logger } from '@kit/shared/logger';const log = logger.child({ route: '/api/hello' });export const GET = defineHandler((c) => { log.info({ method: c.req.method, path: c.req.path }, 'hello'); return { message: 'Hello from Void' };});Children nest: log.child({ orgId }) keeps route and adds orgId. Bindings are serialized once, when the child is created.
What Never to Log
The logger redacts one thing: database errors. A DrizzleQueryError (its message holds the SQL parameters) or a Postgres driver error (its detail repeats key values, as in Key (email)=(ada@example.com) already exists) is logged with only name, code, severity, constraint, table, schema, column, routine, the stack frames and the cause, never its message. So logger.error({ error }, 'Failed to add member') is safe for them.
Everything else is stored as you pass it, visible to anyone with dashboard access. Never log:
- secrets, API keys and tokens (session, reset, invitation, OAuth), including URL paths that carry one: the error middleware logs
/invitation/:id, never the id (apps/web/lib/redact-path.ts; add your own token routes there); - cookies and full request or response headers;
- request or response bodies, form data and uploaded file contents;
- email addresses: log
emailDomain(address)from@kit/shared/utils(acme.dev) asrecipientDomain.
Void prints whatever a handler throws with its own console.error, outside the logger. Before a database error leaves your code, log it, then rethrow withoutQueryDetails(error) from @kit/shared/logger (a plain database query failed error, no cause). The organization services and toHttpError already do.
import { logger, withoutQueryDetails } from '@kit/shared/logger';try { await db.insert(members).values(values);} catch (error) { logger.error({ error }, 'Failed to add member'); throw withoutQueryDetails(error);}Log ids and small facts (userId, orgId, status, counts), not personal data. Keep entries small: Workers Logs truncates an entry above 256 KB, so a large object can cut off the fields you needed.
Common Mistakes
- Interpolating fields into the message.
logger.info(`User ${id} upgraded`)can't be filtered onid. Pass{ userId: id }and keep the message constant. - Logging the whole request or context object. It pulls in headers and cookies. Pick the fields.
- Mixing in
void/log. It takes(message, fields), writes the text undermsginstead ofmessage, and has nochildordebug, so entries from the two loggers don't line up in queries. Use one logger:@kit/shared/logger.
Related
- Logs and Client Errors: reading the logs, and the browsers' error reports.
- Workers Logs: field indexing, the 256 KB limit, sampling and retention.
- Workers best practices: structured logs with a
messagefield, and console levels. - Shared Utilities: the registry, safe redirects, slugs and currency formatting.