/// Logging as an effect: an entry has a level, a message and key=value /// fields, and the handler decides where it goes and which levels pass. /// /// log.info "webhooks: delivered {n}" [] /// log.warn "api: refused" [("reason", reason), ("client", address)] /// /// use <- log.to_console Info // in `main`: info and above, timestamped /// use <- log.silently // in a test: nothing /// /// A line is `{time} {level} {message}` then ` key=value` per field, for /// example `2026-11-05T14:02:11.000Z info GET / 200 8ms client=127.0.0.1`. /// A value that is empty or has a space, `"`, `=`, a backslash or a /// newline is quoted, and a newline in a message is written `\n`, so an /// entry is always one line that splits the same way. Keys are written as /// they are: use plain words. import std/io import std/list import std/ref.{type Ref, type st} import std/string import std/time.{type Timestamp, type clock} /// How much an entry matters, least first: `Debug < Info < Warn < Error`. @derive Eq Ord Show Debug pub type Level { Debug, Info, Warn, Error } /// One logged entry. @derive Eq Show Debug pub type Entry { Entry(level: Level, message: String, fields: List<(String, String)>) } /// Writing an entry to the log. pub effect log { fn emit :: level: Level message: String fields: List<(String, String)> -> () } /// Logs `message` at `Debug`. pub fn debug :: message: String fields: List<(String, String)> -> () / { emit Debug message fields } /// Logs `message` at `Info`. pub fn info :: message: String fields: List<(String, String)> -> () / { emit Info message fields } /// Logs `message` at `Warn`. pub fn warn :: message: String fields: List<(String, String)> -> () / { emit Warn message fields } /// Logs `message` at `Error`. pub fn error :: message: String fields: List<(String, String)> -> () / { emit Error message fields } /// The level's name, lower case: `"debug"`, `"info"`, `"warn"`, `"error"`. pub fn name :: level: Level -> String { match level { Debug -> "debug", Info -> "info", Warn -> "warn", Error -> "error" } } /// The level `text` names, in any case and around spaces (`"WARN"`, /// `" info"`), for a `LOG_LEVEL` setting; `None` for any other text. pub fn level_named :: text: String -> Option { match string.to_lower (string.trim text) { "debug" -> Some(Debug) , "info" -> Some(Info) , "warn" -> Some(Warn) , "error" -> Some(Error) , _ -> None } } // ---- handlers ---------------------------------------------------------------------- /// Runs `action`, writing each entry at `least` or above as a line /// stamped with `time.now`: `Warn` and `Error` to stderr, the others to /// stdout. Both go through one queue, so they stay in order (ADR 0022). pub fn to_console :: least: Level action: fn() -> a / -> a / { handle { action () } with { emit level message fields -> printed least Entry(level, message, fields) } } fn printed :: least: Level entry: Entry -> () / { if entry.level < least { () } else if entry.level < Warn { io.println (line (time.now ()) entry) } else { io.eprintln (line (time.now ()) entry) } } /// Runs `action`, passing each entry at `least` or above to the /// enclosing `log` handler and dropping the others. pub fn at_least :: least: Level action: fn() -> a / -> a / { handle { action () } with { emit level message fields -> passed least Entry(level, message, fields) } } fn passed :: least: Level entry: Entry -> () / { if entry.level < least { () } else { emit entry.level entry.message entry.fields } } /// Runs `action`, its entries dropped. pub fn silently :: action: fn() -> a / -> a / { handle { action () } with { emit _ _ _ -> () } } /// Runs `action`, and answers its result with the entries it logged, in /// order (for tests). pub fn captured :: action: fn() -> a / -> (a, List) / { region { let entries = ref.new [] let result = handle { action () } with { emit level message fields -> kept entries Entry(level, message, fields) } (result, list.reverse (ref.get entries)) } } fn kept :: entries: Ref> entry: Entry -> () / > { ref.update entries fn earlier { [entry, ..earlier] } } // ---- the line ---------------------------------------------------------------------- /// `entry` as one line, stamped `at`: the RFC 3339 time in milliseconds, /// the level padded to five characters, the message, then ` key=value` /// per field. pub fn line :: at: Timestamp entry: Entry -> String { let head = "{stamp at} {padded (name entry.level)} {one_line entry.message}" string.concat [head, ..(list.map entry.fields fn f { " {f.0}={value f.1}" })] } /// `at` in RFC 3339 with exactly three fraction digits, so lines align: /// `2026-11-05T14:02:11.000Z`. fn stamp :: at: Timestamp -> String { let ms = time.unix_ms at let ms_part = ms - floored ms 1000 let whole = time.format (time.from_unix_ms (ms - ms_part)) let digits = "{ms_part}" "{string.slice whole 0 (string.length whole - 1)}.{string.repeat "0" (3 - string.length digits)}{digits}Z" } /// The greatest multiple of `d` at or below `n`. fn floored :: n: Int d: Int -> Int { let r = n % d if r < 0 { n - r - d } else { n - r } } fn padded :: text: String -> String { text <> string.repeat " " (5 - string.length text) } /// A field's value, quoted (backslashes, `"` and newlines escaped) when it /// is empty or would not split cleanly on spaces and `=`. fn value :: text: String -> String { let plain = text != "" && !list.any [" ", "\"", "=", "\n", "\\"] fn c { string.contains text c } if plain { text } else { let inner = replaced (replaced text "\\" "\\\\") "\"" "\\\"" "\"{one_line inner}\"" } } /// `text` with its newlines written `\n`, so it stays on one line. fn one_line :: text: String -> String { replaced text "\n" "\\n" } fn replaced :: text: String old: String new: String -> String { string.join (string.split text old) new }