/// The access log: one line per request, at a level that tells which /// requests to look at. /// /// use <- log.to_console Info /// access.logged (access.defaults ()) req fn { route req } /// /// logs `GET /leaderboard 200 12ms client=127.0.0.1`. A 5xx is `Error`, a /// 4xx `Warn`, any other answer to an asset path (`/static/…`, /// `/favicon.ico`, …) `Debug`, and the rest `Info`: at the default level /// a page view is one line, not one per stylesheet and script. A request /// from htmx carries `htmx=1`, which tells a fragment from a page. /// /// The time is the handler's: a streamed body is still being sent when /// the line is written. A handler that panics writes no line, since a /// cleanup cannot log (ADR 0016); the runtime reports the crash. import client.{type client} import log.{type Level, type log, Debug, Error, Info, Warn} import reply import std/http.{type Request, type Response} import std/list import std/string import std/time.{type clock} /// What the access log treats as an asset (paths that start with one of /// `assets`), and whether a line names the client's address /// (`client=`). pub type Access { Access(assets: List, clients: Bool) } /// `/static/`, `/favicon.ico`, `/.well-known/` and `/robots.txt`, with the /// client's address. pub fn defaults :: -> Access { Access(["/static/", "/favicon.ico", "/.well-known/", "/robots.txt"], True) } /// `access` with no client address on its lines, for an app that keeps /// addresses out of its logs. pub fn without_clients :: access: Access -> Access { Access(..access, clients: False) } /// `handler`'s response to `req`, after logging one line for it. pub fn logged :: access: Access req: Request handler: fn() -> Response / -> Response / { let start = time.monotonic () let resp = handler () let ms = time.in_milliseconds (time.elapsed (time.monotonic ()) start) log.emit (level access req resp.status) "{req.method} {http.path req} {resp.status} {ms}ms" (fields access req) resp } /// The level of the line for `req` answered with `status`. pub fn level :: access: Access req: Request status: Int -> Level { if status >= 500 { Error } else if status >= 400 { Warn } else if asset access (http.path req) { Debug } else { Info } } fn asset :: access: Access path: String -> Bool { list.any access.assets fn prefix { string.starts_with path prefix } } fn fields :: access: Access req: Request -> List<(String, String)> / { let from = if access.clients { [("client", client.address req)] } else { [] } if reply.from_htmx req { list.append from [("htmx", "1")] } else { from } }