Lifecycle Events

Three interception points BoxExpress announces for every request, for logging, metrics and audit trails (0.2.31+).

The three points

BoxLang's own request points (onRequestStart, onRequestEnd, onError) are announced by the Application.bx lifecycle, which a BoxExpress request never enters, so they don't fire here. BoxExpress announces its own instead, and anything can listen with boxRegisterInterceptor() or a module's interceptor:

PointWhenData
onExpressRequestStartonce the request is read, before any middleware or route{ req, method, path, startedAt }
onExpressErrorthe first time an error is thrown or passed to next( err ){ exception, method, path, route, responseSent }
onExpressRequestEndafter the response is sent, whatever the outcome{ method, path, route, status, durationMs }

A slow-request and error log, in the app's own start script:

bxsboxRegisterInterceptor( ( data ) => {
    if ( data.durationMs > 500 ) {
        println( "SLOW #data.route# #data.status# #data.durationMs#ms" )
    }
}, "onExpressRequestEnd" )

boxRegisterInterceptor( ( data ) => {
    println( "ERROR #data.route#: #data.exception.message#" )
}, "onExpressError" )

app = boxExpress()

The data

Key
methodThe request method, as req.method.
pathThe full request path without the query string (/feeds/42), the same value the access log prints. It doesn't change inside a mounted router the way req.path does. It's what the client sent, decoded, so it can hold a newline or a terminal escape: strip control characters before printing it, or print route instead.
routeThe method and the pattern of the route that matched: GET /feeds/:id, not GET /feeds/42. A route in a mounted router has the mount path in front (GET /api/v:version/items/:itemId). <unmatched> when no route matched (below).
reqThe Request itself, on onExpressRequestStart only. Middleware hasn't run yet, so there's no req.session, req.body or req.params.
startedAtThe wall-clock time the request arrived, as a date.
statusThe status code that was sent.
durationMsFrom the request arriving to the response being sent, in milliseconds to two decimal places, from a monotonic clock. It's the same figure the access log and app.metrics() record. For an SSE stream or a download it covers the whole stream.
exceptionWhat was thrown, or whatever was passed to next( err ).
responseSenttrue when the error came after the response had gone out, so the client never saw it. A client that disconnects in the middle of a download or an SSE stream arrives this way; an error monitor will usually want to count these separately, or not at all.

Group metrics by route, never by path: a path has an id in it, so every request would get its own series.

route is <unmatched> for a 404, for a request answered by middleware (a static file, a rate-limit 429, a 413), and for an error thrown before a route was reached. A route that calls next() has passed the request on and no longer counts, so a 404 behind app.all( "/api/*", requireAuth ) is still <unmatched>.

The matched pattern is also on the request as req.routePattern (/feeds/:id, without the method), from the moment a route matches. App-level middleware runs before any route has matched, so it can read it after next() returns or in res.onBeforeSend().

What fires when

  • Start and end pair up. Every request that reaches the app fires onExpressRequestStart once and onExpressRequestEnd once, including a 404, a request refused for its size, one that timed out (status 503) and one whose handler threw.
  • onExpressError fires at most once per request, when the error first appears, whether or not an error-handling middleware then turns it into a tidy response. It comes before onExpressRequestEnd, except for an error raised after the response was sent from another thread; either way that error has responseSent: true. A request timeout isn't an error here: look for status: 503 on the end event.
  • app.inject() fires all three, the same as a real request.
  • WebSockets: an app.ws() upgrade request fires no start or end event, and neither do the messages on an open socket. An error in a route's use middleware does fire onExpressError, with the route <unmatched>.
  • Not covered: a request so malformed that the request object couldn't be built. It gets a bare 500.

Rules for listeners

  • Be fast. Listeners run on the request's own thread, so they can read thread-local context, and onExpressRequestStart runs before the response. Do the minimum (push to a queue, bump a counter) and do anything slow, such as an HTTP call, on a thread of the listener's own.
  • A listener that throws can't break a response. The exception is caught and printed ([BoxExpress] onExpressRequestEnd listener failed: message), and the request carries on. It does stop the other listeners on that point for that request, so catch inside the listener if others must still run.
  • Don't change the request. The events are for observing. Use middleware to change what a request does.
  • Register anywhere, any time. The interceptor pool belongs to the BoxLang runtime, not to an app: a listener hears every BoxExpress app in the process, and can be registered before or after listen().
  • No listeners, no cost. A point nobody listens to is skipped before its data is built, so there's nothing to switch off.