Logging
Write structured JSON logs in production and readable colored logs in development with Logger from @axiljs/observability: levels, child loggers and transports.
On this page9
Logger writes structured log entries: a level, a message and a flat object of context fields. In development it prints colored, human-readable lines; in production it prints one JSON object per line, ready for Loki, Elasticsearch, CloudWatch or any log shipper. It has no dependencies.
1import { Logger } from '@axiljs/observability'
2
3const logger = new Logger({ name: 'UserService' })
4
5logger.info('User created', { userId: 123 })
6logger.error('Database error', { error: err.message, query: 'insert users' })
7
8const reqLog = logger.child({ requestId: 'abc' })
9reqLog.info('Processing') // carries requestId: 'abc'new Logger(options?)
| Option | Type | Default | Description |
|---|---|---|---|
name | string | 'axilJS' | Logger name, included in every entry |
level | LogLevel | 'info' when NODE_ENV=production, otherwise 'debug' | Minimum level written |
format | 'pretty' | 'json' | 'json' when NODE_ENV=production, otherwise 'pretty' | Format of the default console transport |
context | Record<string, unknown> | {} | Fields added to every entry |
transports | Transport[] | [new ConsoleTransport(format)] | Where entries go. Passing this replaces the console transport |
Levels
| Level | Method | Rank |
|---|---|---|
debug | logger.debug(message, context?) | 0 |
info | logger.info(message, context?) | 1 |
warn | logger.warn(message, context?) | 2 |
error | logger.error(message, context?) | 3 |
fatal | logger.fatal(message, context?) | 4 |
Entries below the configured level are dropped before any transport sees them.
const logger = new Logger({ name: 'billing', level: 'warn' })
logger.info('ignored')
logger.warn('written')Log entries
Each call builds one LogEntry and hands it to every transport:
| Field | Type | Description |
|---|---|---|
level | LogLevel | Level of the call |
message | string | First argument |
name | string | Logger name |
timestamp | string | ISO time |
pid | number | process.pid, useful when running several workers |
| ...context | unknown | Logger context, then the call's context |
Production output of logger.info('User created', { userId: 123 }):
{"level":"info","message":"User created","name":"UserService","timestamp":"2026-11-12T09:30:00.000Z","pid":4312,"userId":123}Context fields are spread after the built-in fields, and call context after logger context. A key such as name or level in your context therefore overwrites the built-in value. Avoid those names for your own fields.
Tip
Log err.message and err.stack, not the Error object itself. JSON.stringify() turns an Error into {}.
Child loggers
child(context) returns a logger with the parent's name, format, level and transports, and with context merged over the parent's context. Use it to stamp a request ID, tenant or job ID onto every line from one unit of work.
const jobLog = logger.child({ jobId: job.id, queue: 'emails' })
jobLog.info('started')
jobLog.info('sent', { to: job.data.to })Children share the parent's transport instances, so a FileTransport opened once serves all of them.
Output formats
pretty (development) prints the local time, a colored padded level, [name] and the message. Up to three context fields are appended as key=value on the same line; more are printed below as indented JSON. error and fatal go to console.error, the rest to console.log.
09:30:00 INFO [UserService] User created userId=123json (production) prints JSON.stringify(entry) with console.log, one entry per line.
Override the default either way with format, for example JSON locally when testing a log pipeline:
new Logger({ name: 'api', format: 'json' })Transports
A transport is any object with write(entry: LogEntry): void. The package ships two.
| Class | Constructor | Behavior |
|---|---|---|
ConsoleTransport | new ConsoleTransport(format = 'pretty') | Writes to the console in the given format |
FileTransport | new FileTransport(logPath) | Appends one JSON line per entry to logPath, creating the parent directory if needed |
1import { Logger, ConsoleTransport, FileTransport } from '@axiljs/observability'
2
3const logger = new Logger({
4 name: 'api',
5 transports: [
6 new ConsoleTransport('pretty'),
7 new FileTransport('./logs/api.log')
8 ]
9})FileTransport writes with appendFileSync, which blocks the event loop for each entry. It suits development, CLIs and low-volume services. For busy production APIs, log JSON to stdout and let the platform collect it.
Custom transport
1import type { Transport, LogEntry } from '@axiljs/observability'
2
3class HttpTransport implements Transport {
4 private buffer: LogEntry[] = []
5
6 write(entry: LogEntry): void {
7 if (entry.level === 'debug') return
8 this.buffer.push(entry)
9 if (this.buffer.length >= 100) this.flush()
10 }
11
12 private flush() {
13 const batch = this.buffer.splice(0)
14 fetch('https://logs.example.com/ingest', {
15 method: 'POST',
16 headers: { 'content-type': 'application/json' },
17 body: JSON.stringify(batch)
18 }).catch(() => {})
19 }
20}write() is called synchronously and its return value is ignored. If a transport throws, the error is swallowed and the remaining transports still run, so logging never crashes the application.
Request logging
@axiljs/observability has no logging middleware of its own. A few lines give you one JSON line per request, carrying the request ID from requestContext() and the trace ID from observabilityMiddleware():
1import { Application } from '@axiljs/core'
2import { requestContext } from '@axiljs/runtime'
3import { Logger, Tracer, observabilityMiddleware, getTraceContext } from '@axiljs/observability'
4
5const app = new Application()
6const logger = new Logger({ name: 'http' })
7const tracer = new Tracer({ serviceName: 'my-api' })
8
9app.use(requestContext())
10app.use(observabilityMiddleware({ tracer }))
11app.use((req, res, next) => {
12 const start = Date.now()
13 const log = logger.child({ requestId: req.locals.requestId, traceId: getTraceContext(req)?.traceId })
14 req.locals.log = log
15
16 res.raw.on('finish', () => {
17 log.info('request', {
18 method: req.method,
19 path: req.path,
20 status: res.raw.statusCode,
21 durationMs: Date.now() - start
22 })
23 })
24 next()
25})For quick colored request lines during development only, @axiljs/core also exports requestLogger().
Note
Logger does not redact anything. Keep tokens, passwords and personal data out of log context, or strip them first with redaction.
Related
Was this page helpful?