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?
answer
- a predicate of req and res
- called when the line is due
- mounted routers rewrite one URL
- the :url token's own choice
basics
~20 sPass 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.
solid answer
~40 s`skip` is a function `skip(req, res)`; when it returns a truthy value, morgan writes no line for that request. Without `immediate`, it runs at log time, after the response has finished, so `res.statusCode` is final, which is what makes the documented errors-only filter `skip: (req, res) => res.statusCode < 400` work. Express rewrites `req.url` to be relative to a router's mount point, and if a router mounted at `/health` sent the response, `req.url` can still read `/` when `skip` runs. `req.originalUrl` keeps the path the client asked for, query string included, which is why morgan's own `:url` token prefers it. A format function that returns `null` or `undefined` also skips the line. With `immediate: true`, `skip` runs before any handler, so a status test sees only the default 200.
code
javascript · 13 linesconst express = require('express')
const morgan = require('morgan')
const isHealthCheck = (req) => req.originalUrl.split('?')[0] === '/health'
const health = express.Router()
health.get('/', (req, res) => res.send('ok'))
const app = express()
app.use(morgan('combined', {
skip: (req, res) => isHealthCheck(req) && res.statusCode < 400
}))
app.use('/health', health)go deeper
Remember that skip is a function of req and res and that returning true means no line for that request.
Explain that skip runs after the response without immediate, why req.originalUrl beats req.url, and how to filter on status.
Catch the predicate that silently fails under a mounted router or under immediate mode, and keep failing probes visible.
Set a team rule for what traffic is excluded from access logs and how that exclusion stays consistent with metrics.
## Why health checks are skipped Load balancers and orchestrators probe a **health endpoint** every few seconds on every instance. Each probe is a real HTTP request, so an access log that records everything fills with identical lines that hide the traffic you care about and cost storage. morgan's `skip` option is the switch for dropping them. ## How skip works `morgan(format, { skip })` takes a predicate: - It is called as **`skip(req, res)`**. A truthy return means no line is written; anything falsy means the line is written as usual. - It defaults to `false`, meaning every request is logged. - It runs **at log time**. Without `immediate`, that is after the response has finished (or the connection closed), so `res.statusCode` and the response headers are final. - Each logger has its own predicate. Two morgan instances can use different ones, so one can log everything to a file while another logs only failures to the console. A second way to skip exists for format functions: if the function returns `null` or `undefined`, morgan writes nothing for that request. ## The req.url trap The obvious predicate is `(req) => req.url === '/health'`, and it often fails. Express **rewrites `req.url`** while a request is inside a router mounted with a path, so that the router's routes see a URL relative to their mount point. When the health route lives in a router mounted at `/health` and that router sends the response, `req.url` can still read `/` by the time morgan's `skip` runs, because the response finished while the request was inside the router. `req.originalUrl` is the URL as the client sent it, mount prefix and query string included, and Express never rewrites it. morgan's own `:url` token reads `req.originalUrl` first for exactly this reason. Two details follow: 1. **Strip the query string** before comparing, because a probe may call `/health?full=1`: `req.originalUrl.split('?')[0]`. 2. **Compare the whole path**, not a prefix. `startsWith('/health')` also matches `/healthcare/claims`, a route you probably do want logged. ## Skipping by status Because `skip` runs after the response, it can filter on the outcome as well as the path: | Goal | Predicate | |---|---| | Drop health probes | `(req) => req.originalUrl.split('?')[0] === '/health'` | | Log only errors | `(req, res) => res.statusCode < 400` | | Drop successful health probes only | `(req, res) => req.originalUrl.split('?')[0] === '/health' && res.statusCode < 400` | The last row is worth considering: a **failing** health check is exactly the line you want during an incident. ## Skip and immediate With `immediate: true`, morgan formats the line, and calls `skip`, as soon as the request reaches its middleware, before any route handler has run. At that point `res.statusCode` holds Node's default of `200`, so a predicate such as `res.statusCode < 400` returns `true` for every request and the logger writes nothing. Path-based predicates still work in immediate mode; status-based ones do not. ## Patterns that combine loggers - **Errors to the console, everything to a file**: one `morgan('dev', { skip: (req, res) => res.statusCode < 400 })` and one `morgan('common', { stream: fileStream })`. - **Probes counted, not logged**: skip probes in the access log and expose their count as a metric instead, so a sudden drop in probe traffic is still visible. - **One predicate, shared**: define `isHealthCheck(req)` once and reuse it in every logger, so the access log and any request metrics agree on what a probe is. ## Proving the predicate works A skip rule that silently stops matching is invisible: the log just gets noisier, or quieter, without an error. It is cheap to test, because the `stream` option accepts any object with a `write` method: 1. Create the logger with `stream: { write: (line) => lines.push(line) }`, so lines land in an array instead of standard output. 2. Send `GET /health`, `GET /health?full=1` and an ordinary route through the app with an in-process test client. 3. Assert that only the ordinary route produced a line, and that a health route forced to answer 503 still does. Run the same test after moving the health route into a mounted router; that is exactly the change that breaks a `req.url` predicate. ## Summary `skip(req, res)` decides per request whether a line is written and, without `immediate`, sees the finished response. Test the path with `req.originalUrl`, not `req.url`, and think twice before hiding failed probes.
- Why does morgan's README example skip: (req, res) => res.statusCode < 400 work without immediate but log nothing with it?Without `immediate`, `skip` runs after the response finishes, so `res.statusCode` is the real status. With `immediate: true` it runs before any handler, while `res.statusCode` is still the default `200`, so the predicate returns `true` for every request and every line is dropped.
- How else can you drop a line when the format is a function?Return `null` or `undefined` from the format function and morgan writes nothing for that request. This keeps the filtering next to the fields being built, but it hides the rule inside the formatter; a separate `skip` predicate is easier to reuse and to test.
- skip runs before the route handler, so it can never see the status code.
- Inside skip, req.url always holds the full path the client requested.
- Returning false from skip drops the line.
- With immediate: true, skip can still filter on the final status code.
- Skipping health checks needs a second Express app on another port.