skip to content

Morgan

Express middleware that logs HTTP requests in predefined or custom formats. Interviewers ask where request logging belongs and how to pipe Morgan into your real application logger rather than straight to stdout.

on this pageshow

explore

questions

6

What do morgan's predefined formats dev, tiny, short, common and combined log, and which suits local development versus a production access log?

level: juniorimportance: must knowfreq 35%

answer

  1. five named token strings
  2. two classic web-server layouts
  3. only three carry a timer
  4. dev colors the status

basics

~20 s

morgan's dev format prints method, URL, a status colored by class, response time and body size for local work. tiny and short are compact timed lines; common and combined follow the classic web-server log layouts, combined adding referrer and user agent.

solid answer

~40 s

Each name is a stored format string of tokens. `dev` is `:method :url :status :response-time ms - :res[content-length]` with the status colored green, cyan, yellow or red by class: pleasant in a terminal, but it writes ANSI escape codes into a file. `tiny` carries the same five tokens uncolored, in a different order; `short` adds `:remote-addr`, `:remote-user` and the HTTP version. `common` is the Common Log Format and `combined` appends the quoted `Referer` and `User-Agent` headers, so tooling that already parses web-server access logs can read it. Neither of those two records response time, so production teams often start from `combined` and append `:response-time`, or write their own format. Always name a format: calling `morgan()` without one is deprecated.

code

javascript · 7 lines
javascript
const express = require('express')
const morgan = require('morgan')

const app = express()
app.use(morgan(process.env.NODE_ENV === 'production' ? 'combined' : 'dev'))
app.get('/orders', (req, res) => res.json([]))
app.listen(3000)

go deeper

for a junior

Recall the five names, that dev is colored and meant for a terminal, and that combined adds referrer and user agent to common.

for a middle

Explain that each name is a stored token string, list which formats carry a timer, a timestamp and a client address, and say that the line is written when the response finishes.

for a senior

Pick a production format by the fields you will need when debugging latency or abuse, and spot the dashes that mark aborted requests or an immediate logger.

for a principal

Treat the format as a contract with whatever parses the logs: compatibility with existing tooling versus the fields, like latency and request id, the classic layouts lack.

## What a predefined format is `morgan(format, options)` returns a middleware function that writes one line per HTTP request. The `format` argument can be a **predefined name**, a **format string** built from tokens, or a **format function**. A predefined name is nothing more than a format string the module registered under that name with `morgan.format(name, string)`. When you pass `'combined'`, morgan looks the name up, compiles the string into a function once, and calls that function for every request. A **token** is a placeholder such as `:method` or `:res[content-length]`; the part in square brackets is an argument passed to the token. In a format string, a token that has no value prints as `-`, which is why many lines contain dashes. ## The five formats side by side | Name | Token string | Example line | |---|---|---| | `dev` | `:method :url :status :response-time ms - :res[content-length]` (status colored) | `GET /orders 200 4.512 ms - 312` | | `tiny` | `:method :url :status :res[content-length] - :response-time ms` | `GET /orders 200 312 - 4.512 ms` | | `short` | `:remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms` | `::1 - GET /orders HTTP/1.1 200 312 - 4.512 ms` | | `common` | `:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]` | `::1 - - [10/Oct/2026:07:27:21 +0000] "GET /orders HTTP/1.1" 200 312` | | `combined` | the `common` string plus ` ":referrer" ":user-agent"` | the `common` line plus `"-" "-"` | `common` is the long-standing **Common Log Format** (CLF) of web servers, and `combined` is the **Combined Log Format** that extends it. Their value is compatibility: log shippers, parsers and analysis tools recognise them without configuration. ## Reading the dev format The `dev` format is designed for a developer watching a terminal: - The status is **green** for 2xx, **cyan** for 3xx, **yellow** for 4xx and **red** for 5xx; 1xx codes and responses that never sent a status stay uncolored. - The colors are ANSI escape sequences written into the line itself. morgan does not check whether its output is a terminal, so a file or a log aggregator receiving `dev` lines stores those raw sequences. - The order puts the timer before the body size, the reverse of `tiny`. ## What each layout leaves out Choosing a format is mostly choosing which fields you will never have: - **Response time** appears only in `dev`, `tiny` and `short`. Neither `common` nor `combined` records how long a request took. - **Client address and user** appear in `short`, `common` and `combined`. `:remote-addr` reads `req.ip` when it exists, so in Express it follows the app's proxy settings; otherwise it falls back to the socket address. `:remote-user` is the user name from a Basic `Authorization` header. - **A timestamp** appears only in `common` and `combined`, through `:date[clf]`. - **Referrer and user agent** appear only in `combined`. - **A request id** appears in none of them; you add it with a custom token. ## Choosing for development and production 1. **Locally**, `morgan('dev')` gives a short, colored line per request that is easy to scan while you click through an app. 2. **In production**, use `combined` when an existing pipeline already parses that layout, accepting that it has no latency field. 3. **Otherwise**, write your own format string, for example the `combined` string with ` :response-time ms` appended, or a format function that builds an entry for the application's logger. 4. **Never omit the format.** `morgan()` with no format prints a deprecation warning (`undefined format: specify a format`) and falls back to a legacy `default` layout that is itself deprecated in favour of `combined`. ## When the line is written By default morgan writes the line when the **response finishes**, not when the request arrives. It records the start time when its middleware runs, notes when the response headers go out, and formats the line once the response is complete, or once the connection closes if the client gave up. That is why the status, size and timing are known, and why a request's access line appears after anything the route handler logged. The `immediate` option moves the write to request time, at the cost of those response fields. When a client disconnects before any response is sent, the line is still written, but `:status`, `:res[content-length]` and `:response-time` all print `-`.

  • Why would a team append :response-time to combined rather than switch to short?
    `short` has a timer but drops the timestamp, the quoted request line, the referrer and the user agent, so parsers that expect the Combined Log Format cannot read it. Appending ` :response-time ms` to the `combined` string keeps the familiar fields first and adds latency at the end; a strict parser may need its pattern extended to accept the extra field.
  • What does morgan log for a request whose client disconnects before any response is sent?
    Without `immediate`, morgan still writes a line when the connection closes, but `:status`, `:res[content-length]` and `:response-time` print `-` because no headers were ever sent; in `dev` the status is left uncolored. A run of dash statuses is worth watching: clients are giving up before the handler answers.

  • The combined format records how long each request took.
  • dev is fine for production files because morgan strips colors when not on a terminal.
  • common and combined differ only in how the date is written.
  • morgan writes each line when the request arrives, before the handler runs.
  • Calling morgan() with no arguments selects the dev format.
open as a page

With morgan, how do you add a request id to every access-log line, and when do you need morgan.token rather than the built-in :req[header] token?

level: middleimportance: must knowfreq 30%

basics

~20 s

If the id arrives in a request header, the built-in :req[x-request-id] token prints it. If your code generates the id and stores it on req, register morgan.token('id', (req) => req.id) once and put :id in the format string.

open as a page

With morgan's skip option, how do you keep health-check requests out of the access log, and why can a test on req.url miss them?

level: middleimportance: should knowfreq 25%

basics

~20 s

Pass skip: (req) => req.originalUrl.split('?')[0] === '/health'. morgan calls skip when the line is due, after the response finishes; if a router mounted at /health sent it, req.url can still read '/' then, while req.originalUrl keeps the full path.

open as a page

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?

level: seniorimportance: should knowfreq 20%

basics

~20 s

With 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.

open as a page

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%

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.

open as a page

As the lead setting an access-log standard for a team's Express services, would you standardise on morgan's combined format or a shared format function emitting structured entries, and which fields must every entry carry?

level: principalimportance: should knowfreq 15%

basics

~20 s

Keep combined only where an existing parser expects it. Otherwise ship one shared morgan 1.12+ format function writing one structured entry per request to the app logger: request id, method, path, status, both timers, size; never credentials or query strings.

open as a page