Records / Logging
Logging
A store's logger prints each line to the console as any logger does, and keeps
it in records.db too, where a query finds it next week. A log call never
waits and never throws: under load a line is dropped and counted, never a
request slowed.
const log = store.logger('api', { redact: secrets })
log.info('signed in', { user: 42 })
log.warn('slow request', { route: '/notes', ms: 1200 })
log.error('charge failed', { order: 7, error }) // an Error is kept as its stack
const request = log.with({ requestId }) // every line of `request` carries it
request.debug('cache miss', { key })log = store.logger("api", redact=tinystore.secrets)
log.info("signed in", user=42)
log.warning("slow request", route="/notes", ms=1200)
log.error("charge failed", order=7, error=error) # an exception is kept as its traceback
request = log.bind(request_id=request_id) # every line of `request` carries it
request.debug("cache miss", key=key)handler := records.NewHandler(store, "api", console.Redact(console.Secrets...))
log := slog.New(handler)
log.Info("signed in", "user", 42)
log.Warn("slow request", "route", "/notes", "ms", 1200)
log.Error("charge failed", "order", 7, "error", err)
request := log.With("request_id", requestID)
request.Debug("cache miss", "key", key)let log = store.logger("api").redact(SECRETS).layer()?;
tracing_subscriber::registry().with(log.clone()).init(); // a clone is the same logger
tracing::info!(user = 42, "signed in");
tracing::warn!(route = "/notes", ms = 1200, "slow request");
let span = tracing::info_span!("request", request_id = %request_id).entered(); // its lines carry it16:42:24.094 INFO api signed in user=42
16:42:24.094 WARN api slow request requestId=r-1 route=/notes ms=1200What a line is
A line is an event named log of the logger's stream, with the call's
level, its text as the message and what it gave as the fields. What
with gave is the context (bind in Python, With in Go, a span in
Rust). What an event carries lists each
part.
A key that a nested with gives again takes the new value where the outer
one stood, as an object spread does: the line prints it once, the event keeps
it once, and a read's where finds it by the new value alone.
So store.events('api') reads the logger's lines beside any events appended
to the same stream, and every read finds both. See Reading.
A program that names its components by a path keeps the path itself, in two
lines, since with replaces the key:
const named = (log: Logger, path: string) => log.with({ component: path })
const queue = named(log, 'moodle.queue')Errors
A field takes a value of any type, and an error is a field like another. In
TypeScript an Error is kept as its stack, then Caused by: and the stack of
each cause, ten at most, and of each of an AggregateError's errors. An
Error inside an object is written the same way, not as {}. Python keeps an
exception's traceback, its causes included, and Go and Rust an error's text.
log.error('sync failed', { err: new Error('moodle 502', { cause: timeout }) })16:42:24.094 ERROR api sync failed
err: Error: moodle 502
at sync (moodle.ts:40:11)
Caused by: Error: timeout
at fetch (http.ts:7:5)Something thrown that is not an Error, a string or an object, goes in a field
as it is: log.error('sync failed', { err: thrown }).
Each language's own logger
| Language | The store's logger is |
|---|---|
| TypeScript | store.logger(name): debug, info, warn, error, with, event |
| Python | store.logger(name) with logging's levels and warning, bind; store.log_handler(name) for a program on logging |
| Go | records.NewHandler(store, name), a slog.Handler: slog.New(handler) |
| Rust | store.logger(name).layer(), a tracing layer; spans give the context |
A Python program that already logs through logging keeps its calls:
logging.getLogger("worker").addHandler(store.log_handler("worker")) # a record's extra becomes its fieldslog_handler takes the options of store.logger, level among them, as one
level or as {"store": …, "console": …}. It follows LOG_LEVEL and the
config log as the logger does. Leave the handler's own logging level unset: it drops a
record before the store's logger sees it, so neither of them could lower it.
Go's handler passes testing/slogtest, so any slog code logs into the
store unchanged.
Never waits
- A line is printed as it is logged, before anything is written.
- It is kept within a second: a logger writes what it holds every second,
sooner once half its buffer waits, at
flush()and when the store closes. - A line that finds the buffer full is dropped and counted in
dropped, and said on the console at most once in ten minutes (NOT-09).
Logging is not where a program should wait for a disk. What must not be lost,
an audit entry, a payment, is an event that append writes and
waits for.
Hiding secrets
redact hides a value wherever its key names a secret, on the console and in
the store, at any depth:
{"msg":"signed in","user":42,"apiKey":"[redacted]","url":"postgres://u:[redacted]@h/db"}- A key is split into words, and a name hides it when the name's words stand
together in it:
'api key'hidesapiKey,api_keyandAPI-KEY;'token'hidesbot_tokenand nottokens_used. secretsis the usual names: passwords, tokens, keys, cookies,authorizationand the like.- A URL's password inside any value is hidden too, unless
keepUrlPasswords. replace: (key, value) => valueruns on each field before it is hidden, for what a name cannot catch. Areplacethat returnsundefinedleaves the field out (Nonein Rust, an emptyslog.Attrin Go), so returnvaluefor every field it doesn't change. In Python,replacecan't leave a field out: aNonethat it returns is kept asnull.- A message's text is left as it is: put secrets in fields, never in the
message, so
redactcan find them.
In Rust, a field logged with ? reaches the logger as one string, the
value's Debug text. redact hides a URL's password inside that string, but
it doesn't look for a secret's key in it. Log a secret as a field of its own,
so that its key hides it:
tracing::info!(client = ?client, "connected"); // client="Client { id: 7, api_key: \"sk-4f2a\" }": the key shows
tracing::info!(client = client.id, api_key = %client.api_key, "connected"); // client=7 api_key=[redacted]Options
A logger also takes level, the least level kept and printed, which can
print less than it keeps, and the options of
Console output, which say how a line looks.
| Option | Unless given | Does |
|---|---|---|
redact | nothing hidden | the names of secrets |
source | none | adds the function, file and line of the call |
buffer | 1,024 lines | the lines held between writes |
keep | the stream's | how long the stream keeps its events, 14 days unless set |
A store's logger reads its options through the config log too: a change of
its level in any process sets it for every logger of the store, as
Live settings change any setting. That level is the one
kept, and the one printed too unless level has a console part. The config
log has no console part, because a console belongs to one process.
Events from a logger
log.event('signup', { plan: 'pro' }) // an event named signup: no level, no messagelog.event("signup", plan="pro")handler.Event("signup", "plan", "pro")log.event("signup", &Signup { plan: "pro" });event writes an event with a name of its own, as a line is written: at
once, and dropped under load. Logger or append?
says which to use.
See also
- Records: the engine's overview.
- Console output: pretty and JSON, and a logger without a store.
- What it is doing in the Handbook.