Skip to content

Module Logger Pattern ​

Problem ​

Log entries from different modules are mixed in the output, making it hard to filter by origin. Each module should create its own logger with a fixed namespace so entries can be filtered without additional context.

Solution ​

Use createLogger(name) to create a fixed-namespace logger for each module and export it as a named constant.

ts
import { createLogger } from '@vielzeug/rune';

export const log = {
  api: createLogger('api'),
  auth: createLogger('auth'),
  db: createLogger('db'),
};

log.api.info('GET /users');
log.auth.warn('token expiring');

Pitfalls ​

  • Using the same namespace string in two different modules makes their log entries indistinguishable. Use dot-joined namespaces such as app.orders.service to keep scopes distinct.
  • Creating the logger at module load time means its namespace and bindings are fixed for that module instance. Prefer request-scoped child loggers when fields vary per request.
  • Structured context is the second argument: use logger.info('event', { userId }). The first argument is always the message string.