An Express API logs with morgan and immediate: true, and every line shows '-' for status and timing; why, and what do :response-time and :total-time each measure?
answer
- logged on arrival, not on finish
- no response exists yet
- headers written versus response finished
- streamed bodies widen the gap
basics
~20 sWith immediate: true morgan writes the line when the request reaches it, before any response exists, so :status, :res[...] and both timers print '-'. Without it, :response-time ends when headers are written and :total-time when the response finishes.
solid answer
~40 sBy default morgan records a start time when its middleware runs, hooks the moment the response headers are written, and formats the line when the response finishes or the connection closes. `immediate: true` formats the line on arrival instead: the line exists even if the process crashes mid-request, but `:status`, `:res[...]`, `:response-time` and `:total-time` have nothing to read and print `-`. `:response-time` is the time from morgan's middleware to the **headers** being written; `:total-time` runs to the moment the line is formatted, after the **response has finished**. For a handler that sends headers early and streams a large body, the first can read under a millisecond while the second reads seconds. Both take an optional digits argument, three decimals by default. To get both arrival and outcome, mount two loggers, one with `immediate`.
code
javascript · 11 linesconst express = require('express')
const morgan = require('morgan')
const app = express()
app.use(morgan('[start] :method :url', { immediate: true }))
app.use(morgan(':method :url :status :response-time ms :total-time ms'))
app.get('/export', (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/csv' })
setTimeout(() => res.end('id,total\n'), 2000)
})go deeper
Recall that morgan normally logs when the response finishes and that immediate logs on arrival without status or timing.
Explain the start, headers and finish moments morgan records, and which timer ends at which one.
Read dashes and timer gaps as evidence: an immediate logger, an aborted client, or a slow body behind a fast first byte.
Decide whether in-flight visibility justifies a second line per request, and which timer the team's latency objectives use.
## The default timeline morgan's middleware does three things per request when `immediate` is not set: 1. **Records a request start time** with a high-resolution clock the moment its middleware runs. 2. **Registers a headers hook**, so that when the response headers are written it records a response start time. 3. **Registers a finish listener**, so that when the response has been fully written, or the connection has closed, it formats and writes the line. Everything response-shaped in the line, the status, response headers and both timers, is available because the line is formatted at the end. ## What immediate: true changes With **`immediate: true`** morgan skips steps 2 and 3 and formats the line straight away, before calling `next()`. The line is written before any route handler runs. - **Gained**: a line exists for every request that reaches morgan, even if the process crashes or the handler never answers. That is the documented purpose of the option. - **Lost**: `:status`, `:res[header]`, `:response-time` and `:total-time` have no data. In a format string each prints `-`; in a format function each returns `undefined`. - **Also affected**: a `skip` predicate runs at the same early moment, so it sees `res.statusCode` at its default of 200. So a line such as `GET /orders - - ms` is not a bug in the handler; it is the immediate logger working as designed. ## The two timers | Token | Starts | Stops | Misses | |---|---|---|---| | `:response-time[digits]` | when morgan's middleware runs | when the response headers are written | the time spent sending the body | | `:total-time[digits]` | when morgan's middleware runs | when the line is formatted, after the response finished | nothing after the response | Both default to **three decimal places** (microsecond precision); `:response-time[0]` rounds to whole milliseconds. Both print `-` when the response never wrote headers, for example when the client disconnected first. The gap between them is the **body transfer**. A handler that calls `res.writeHead(200)` and then streams an export for two seconds produces a `:response-time` close to zero and a `:total-time` around 2000. A slow client on a large JSON payload shows the same pattern. Alerting on `:response-time` alone hides both cases. Neither timer starts at the socket. Time spent before morgan's middleware ran, in middleware mounted earlier or waiting on a busy event loop, is outside both numbers. ## Aborted and hung requests - A **client that disconnects** before any response: without `immediate`, the finish listener still fires on close, so a line is written with `-` for status, size and both timers. - A **handler that never responds and a client that never leaves**: without `immediate`, no line is written at all until the connection closes. This is the gap `immediate` fills. ## Getting both views morgan can be mounted more than once, and its README lists "log entry on request and one on response" as a use. Two instances give a request line on arrival and an outcome line on finish: - `morgan('[start] :method :url', { immediate: true })` - `morgan(':method :url :status :response-time ms :total-time ms')` The cost is two lines per request and a join on some shared key, such as a request id token, to pair them. Most services keep a single finish-time logger and accept that a crash loses the in-flight lines. ## Timers in a format function The same tokens are available inside a format function, with the digits argument passed positionally: - `tokens['response-time'](req, res)` returns a string such as `'4.512'`; `tokens['response-time'](req, res, 0)` returns `'5'`. - `tokens['total-time'](req, res, 1)` returns one decimal place. - Each returns `undefined`, not `-`, when there is nothing to measure, as in immediate mode or after an aborted request, so convert to a number only after checking for that. Because `:total-time` is computed when the line is formatted, anything that runs before that inside morgan's finish callback, such as a slow `skip` predicate, is counted in it. ## Diagnosing the dashes 1. **Every line has `-` for status and timing**: the logger uses `immediate: true`. 2. **A few lines have `-`**: clients aborted before the response started; correlate with timeouts upstream. 3. **`:response-time` small, `:total-time` large**: the body or the client is slow, not the handler's time to first byte.
- When is immediate: true worth its lost fields?When you must know a request arrived even if the process dies or the handler never answers: debugging crashes, hangs or requests that exhaust memory. Usually it runs alongside a normal finish-time logger rather than replacing it, since the finish line carries the status and timing that day-to-day operation needs.
- Why might :response-time look healthy while users report slow downloads?`:response-time` stops when headers are written, so a handler that sends headers early and then streams or pipes a large body looks fast. `:total-time` runs until the response finishes and shows the transfer. Record both, and alert on the one that matches what users experience.
A waiter's log. With immediate, the note is written as guests sit down, so it cannot say what they ordered or how long service took. By default it is written as they leave: response time is when the first plate reached the table, total time when the last one did.
- :response-time measures until the last byte of the body is sent.
- immediate: true only changes when the line is written, not what it can contain.
- :total-time and :response-time are always within a millisecond of each other.
- If the client disconnects mid-request, morgan writes no line for it.
- morgan's timers start when the server accepts the connection.