skip to content

With morgan, how do you route access-log lines into the application's structured logger through the stream option, and what changes when that stream is in object mode?

level: seniorimportance: should knowfreq 30%

answer

  1. default is process.stdout
  2. anything with a write method
  3. a trailing newline per line
  4. writableObjectMode passes objects through

basics

~20 s

Pass stream: { write: (line) => logger.info(line.trimEnd()) }; morgan calls write with each formatted line plus a newline. Since morgan 1.12.0, a stream whose writableObjectMode is true receives a format function's returned object as-is, with no newline.

solid answer

~40 s

`stream` defaults to `process.stdout`, but morgan only ever calls `stream.write(...)`, so any object with a `write` method works. In line mode it calls `write(line + '\n')`, so the adapter trims the newline and hands the string to the logger as one message, without fields. Since morgan 1.12.0, if `stream.writableObjectMode` is `true` and the format function returns an object, that object is written unchanged with no newline, so the logger receives real fields. Two details matter there: token values are strings (`tokens.status` gives `'200'`, not `200`) and are escaped for line logs, so a quote arrives as `\"`; and a token with no value gives `undefined`, not `-`. Without the flag, a returned object is stringified to `[object Object]`.

code

javascript · 18 lines
javascript
const morgan = require('morgan')
const logger = require('./logger') // the application's structured logger

const num = (v) => (v === undefined ? undefined : Number(v))

const accessLog = morgan((tokens, req, res) => ({
  msg: 'http request',
  requestId: req.id,
  method: req.method,
  url: req.originalUrl,
  status: num(tokens.status(req, res)),
  responseTimeMs: num(tokens['response-time'](req, res)),
  totalTimeMs: num(tokens['total-time'](req, res))
}), {
  stream: { writableObjectMode: true, write: (entry) => logger.info(entry) }
})

module.exports = accessLog

go deeper

for a junior

Know that stream defaults to process.stdout and that any object with a write method can receive morgan's lines.

for a middle

Explain the trailing newline in line mode, the adapter that trims it, and why the logger then holds one string, not fields.

for a senior

Wire object mode correctly, convert token strings, handle undefined and double escaping, and choose levels by status.

for a principal

Decide whether the access-log contract is a text layout parsed downstream or structured fields owned by the application logger.

## What the stream option is `morgan(format, { stream })` decides where finished log lines go. The default is **`process.stdout`**. morgan does not require a real Node.js `Writable`: it only ever calls **`stream.write(value)`**, so any object with a `write` method is accepted. That makes the option the natural seam for sending access lines to the application's own logger, the one that already adds timestamps, levels, service names and shipping. ## Line mode: strings with a newline With a format string or a format function that returns a string, morgan calls `write` with the line **plus a trailing `\n`**. An adapter therefore looks like this: - `write: (line) => logger.info(line.trimEnd())` removes the newline so the logger does not store it as part of the message. - The logger receives **one opaque string**. A `combined` line stays a `combined` line inside the logger's message field; nothing is split into fields. - Wrap the logger call in an arrow function rather than passing a method such as `logger.info` directly, because morgan calls `stream.write(...)` and a detached method may lose the receiver it relies on. Line mode is enough when the log pipeline already parses the text format downstream. ## Object mode: structured entries Since **morgan 1.12.0** a stream can receive objects. Two conditions must both hold: 1. The stream has **`writableObjectMode: true`**. 2. The format is a **function** that returns an object. morgan then calls `write(entry)` with that object unchanged and **no newline**. If the stream is not in object mode, the object is concatenated with `'\n'` and the logger receives the useless string `[object Object]`. Returning `null` or `undefined` from the function still skips the line in either mode. ## What the object's values look like A format function gets `(tokens, req, res)`, where `tokens` is the table of every registered token. Three facts shape the entry: | Source | Type you get | Missing value | |---|---|---| | `tokens.status(req, res)` | string, e.g. `'200'` | `undefined` | | `tokens['response-time'](req, res)` | string, e.g. `'4.512'` | `undefined` | | `req.method`, `req.originalUrl`, `req.id` | the raw property | whatever the property holds | - **Convert numbers yourself.** A status of `'200'` and a duration of `'4.512'` are strings; convert them, guarding against `undefined`, before a log backend indexes them as text. - **No dash substitution.** The `-` placeholder belongs to compiled format strings. In a function a missing token is `undefined`, and a JSON serialiser typically omits that key. - **Token output is escaped for text lines.** morgan escapes control characters, backslashes and double quotes in every token's string result, so a user agent containing `"` arrives as `\"`. A JSON logger will escape that again. For fields where the raw value matters, read `req` or `res` directly and let the logger do the encoding. ## Choosing a level per request In line mode the stream sees only the string, not `req` or `res`, so it cannot pick `warn` for 4xx and `error` for 5xx. Two ways out: 1. **Object mode**: include the numeric status in the entry and let the `write` adapter choose the level from it. 2. **Several morgan instances**, each with a `skip` predicate on `res.statusCode` and a stream bound to one level. ## Failure signatures Each wiring mistake leaves a recognisable trace in the logger's output: - **`[object Object]` in every entry**: the format function returns an object but the stream lacks `writableObjectMode: true`. - **A blank line after every message**: a line-mode adapter forwards the string without trimming its trailing newline. - **`NaN` for status or duration**: `Number(...)` was applied to a token that returned `undefined`, typically for an aborted request; guard the conversion. - **Backslashes before quotes in user agents or referrers**: token output was escaped for a text line and then encoded again by the logger. - **Duplicate entries per request**: two morgan instances, or morgan plus a request hook in the logger, both write an access entry. ## Operational notes - `write` is called **synchronously** from morgan's finish handler. A slow or throwing adapter runs on the request's tail; keep it to a hand-off to the logger. - One morgan instance writes **one line per request**. Adding a second instance, or letting the application logger also log requests, duplicates entries. - The deprecated `buffer` option batches writes on a timer; leave buffering to the logger instead. ## Summary The stream option is a single `write` call per request. Use a trimmed string adapter when the text format is the contract, and object mode with a format function when the application logger should receive fields.

  • Why does a user agent containing a double quote arrive as \" in the object-mode entry?
    morgan escapes the string result of every token for line-oriented logs, turning quotes, backslashes and control characters into escape sequences. That protects text lines from forgery, but in object mode the JSON logger escapes the value again. Read the raw `req.headers['user-agent']` in the format function when the logger encodes values itself.
  • How do you log 5xx responses at error level when the stream only receives a string?
    Either switch to object mode and put the numeric status in the entry, so the `write` adapter can choose the level, or mount several morgan instances whose `skip` predicates split by `res.statusCode`, each writing to an adapter bound to one level.
  • What does the logger receive if the format function returns an object but the stream lacks writableObjectMode?
    The string `[object Object]` followed by a newline: without the flag morgan treats the result as a line and concatenates it with `'\n'`. Nothing fails loudly, so the mistake usually surfaces as a log full of identical, empty-looking entries.

  • The stream option must be a real Node.js Writable stream.
  • morgan strips the trailing newline before calling stream.write.
  • Returning an object from a format function sends JSON to process.stdout.
  • In object mode tokens.status returns the status as a number.
  • A token with no value gives - inside a format function too.

Assumes morgan 1.12.0 or later: HISTORY.md lists object pass-through for streams in object mode in 1.12.0; before it the stream always received a string line.