Custom Formatting
Create custom log message formats
Customize log message formats using placeholders to match your logging needs.
If you omit customLogFormat, Logixlysia uses a built-in default that includes the fox {icon}, optional {service} prefix, colored method and duration, {speed} for slow requests, and other common fields.
Basic Usage
logixlysia({
config: {
customLogFormat: '{now} {level} {duration} {method} {pathname} {status}'
}
})
Available Placeholders
| Placeholder | Description |
|---|---|
{now} |
Current date and time as ISO 8601; local HH:MM:ss.SSS on a TTY when neither customLogFormat nor timestamp is set |
{level} |
Log level (DEBUG, INFO, WARNING, ERROR); with colors, level-colored background chip |
{duration} |
Request duration (e.g. 12ms, 1.5s); with colors, green / yellow / red based on slowThreshold and verySlowThreshold |
{method} |
HTTP method, padded to seven characters in every format |
{pathname} |
Request path (alias: {path}); includes query string if logQueryParams is enabled |
{query} |
Raw query string (e.g. ?id=123) |
{status} |
Response status code |
{statusText} |
Status text from Node’s http.STATUS_CODES (e.g. Not Found for 404) |
{message} |
Custom message |
{icon} |
With colors on a TTY, the Logixlysia fox 🦊 in a level-colored background (green INFO, yellow WARNING, red ERROR, blue DEBUG). When useColors is off, NO_COLOR is set or output is not a TTY, the level as a word padded to five characters: DEBUG, INFO , WARN , ERROR |
{speed} |
When duration ≥ verySlowThreshold, appends ⚡ slow (yellow with colors) |
{service} |
From config.service, rendered as [name] (dim with colors); empty if unset |
{context} |
JSON string of data.context when the context tree is off or context is empty; omitted on the main line when the context tree is shown (see below) |
{ip} |
Client IP address (from x-forwarded-for or x-real-ip; empty when testing locally without these headers) |
{epoch} |
Unix time in milliseconds |
{requestId} |
Request ID when requestId is on; empty otherwise |
The line is written once Elysia has produced the response, so it carries the status the client received, even when a mapResponse, onError or onRequest hook decided it. For a generator (streaming) handler the line is written when the body finishes, so {duration} covers the whole stream, and a throw inside the body produces an error line with the status the headers carried. If the client disconnects from a long-lived stream such as server-sent events, the plugin writes the line as soon as the request is aborted, even while the generator is still waiting for its next value. That line carries the status the client was sent (usually 200, with no disconnect marker), and {duration} runs up to the disconnect. Each stream still gets exactly one line. A generator whose finally block throws during cleanup is logged as an ERROR line, whether the body was cancelled before or after its first read. A Response with a streaming body, or a generator whose first value is a ReadableStream, is logged when the response is created. With aot: false, or with the plugin mounted inside group() or guard(), the plugin’s hooks write the line instead, when the handler returns or throws.
Examples
Minimal Format
customLogFormat: '{method} {pathname} {status}'
Output:
GET /api/users 200
Branded line with {icon} and {service}
Use {icon} for the level: the Logixlysia fox in a level-colored chip when colors and a TTY are available, and the level word otherwise. Pair with service in config:
logixlysia({
config: {
service: 'my-api',
customLogFormat:
'{now} {service}{icon} {method} {pathname} {status} {duration} {message}{speed}'
}
})
With useColors: false or non-TTY output, a line can look like:
2025-04-13T15:00:19.123Z [my-api] INFO GET /api/users 200 12ms User viewed profile
On a color terminal, the fox appears inside a colored chip by level, and slow requests append ⚡ slow via {speed} when duration ≥ verySlowThreshold (default 1000).
Status text
customLogFormat: '{method} {pathname} {status} {statusText}'
Example values: 404 Not Found, 500 Internal Server Error.
Timestamp Format
Configure timestamp format separately:
logixlysia({
config: {
customLogFormat: '{now} {level} {method} {pathname}',
timestamp: {
translateTime: 'yyyy-mm-dd HH:MM:ss'
}
}
})
Context tree
When showContextTree is true (default), object context passed to logger.info / warn / error / debug is printed under the main line as tree branches, instead of being inlined into {context} on that line.
- Each row is two spaces,
├─or└─, the key (cyan when colors are on), two spaces, then the value. - For
ERRORandWARNINGlogs, anerrorrow is appended when an error object is present (parsed message). The row is left out when the main line already ends with the same message, so a failed request prints its message once. - Set
contextDepth(default2) to flatten nested objects into dotted keys (e.g.user.id) up to that depth. - On a TTY, a string value longer than 200 characters is cut to 200 and ends in
… (<length> chars). Piped stdout, files and transports get the whole string.
logixlysia({
config: {
showContextTree: true,
contextDepth: 3
}
})
Example (no ANSI colors), after a main line like … GET /orders 500 3ms Checkout failed:
├─ orderId ord_123
└─ error Card declined
Structured Error Logs
Logixlysia natively supports structured errors when thrown exceptions contain specific troubleshooting fields:
code: A stable, machine-readable identifier for the failure (e.g.PAYMENT_DECLINED).why: Explains the root cause of the error.fix: Suggests actionable remediation.link: Provides a URL to documentation or troubleshooting help.internal: Log-safe diagnostic metadata (e.g. error codes, non-sensitive context).cause: The underlying error, set withnew Error(message, { cause })or thecauseoption ofHttpError. It reaches transports aserror.causeand prints in the console asCaused by:lines, up to three levels in both.
If a caught error contains any of the code, why, fix, link or internal fields, they are automatically extracted and rendered under the error. namespace (error.code, error.why, error.fix, error.link and error.internal) as individual tree branches.
An error that reaches the log with a stack also gets error.at, the first stack frame outside node_modules, as <file>:<line>:<column> relative to the working directory. It is console only: transports receive the full stack instead. A 4xx HttpError carries no stack, so it has no error.at.
// Custom error implementation
class CheckoutError extends Error {
why = 'Card declined by issuer due to insufficient funds.'
fix = 'Please try a different credit card or payment method.'
link = 'https://docs.example.com/payments/declined'
internal = { gatewayCode: 'NSF', raw: '...' }
}
throw new CheckoutError('Payment failed')
Console output tree under the line that ends in Payment failed:
├─ orderId ord_123
├─ error.why Card declined by issuer due to insufficient funds.
├─ error.fix Please try a different credit card or payment method.
├─ error.link https://docs.example.com/payments/declined
└─ error.internal {"gatewayCode":"NSF","raw":"..."}
Error causes
When you wrap a lower-level failure, pass it as cause to keep the original error on the log line. Logixlysia normalizes an Error cause the same way as the error itself, keeping its name, message, and any structured fields (code, why, fix, link, internal). A nested cause chain is followed up to three levels deep and cut after that. A primitive cause, such as a string, is logged as is.
app.post('/orders', async () => {
try {
await db.insert(order)
} catch (err) {
throw new Error('Could not save order', { cause: err })
}
})
Console output tree under the line that ends in Could not save order. Each cause is a Caused by: <name>: <message> line, indented one step deeper than the one before it, and followed by an at line with the first frame outside node_modules when the cause has a stack:
├─ error.at src/routes/orders.ts:6:11
├─ Caused by: Error: connection to db timed out
└─ at src/db.ts:14:9
The console follows the chain up to three causes, stops at a cause it has already shown, and prints a string or object cause as its text or JSON. With autoRedact on, a cause message is redacted like the top message.
Transports receive the cause as meta.error.cause, with the name and message of the original error.
HttpError accepts cause in its init object. Like internal, the cause is written to the log only and is never serialized into the response body:
import { HttpError } from 'logixlysia'
throw new HttpError(502, 'Upstream failed', {
code: 'UPSTREAM_FAILED',
cause: new Error('connection reset')
})
See HttpError for the full init options.
Set showContextTree: false to disable the tree and put stringified context back on the main line via {context} when you include that token.
Error Log Formatting
The customLogFormat applies to both regular access logs and error logs. When an error occurs (like validation errors or exceptions), the same formatting rules apply, ensuring consistent log output across all log levels.
Best Practices
- Keep formats concise for readability
- Include essential information only
- Use consistent formatting across environments
- Consider log parsing requirements when designing formats
- Error logs will include the error message in the
{message}placeholder