21 KiB
Plan: logging
Written 2026-10-07, and brought up to date 2026-10-20 for threads, owners and
function, std::time, and what probing showed. This is a proposal.
std is yours, so the decisions at the end are yours to make. Nothing of it is built
yet but the clock, which std::time brought on 2026-10-12.
Comes after the ffi plan, now built: std::sys is system, and @foreign and
@link are extern sections.
What it is: a program saying what it's doing, at levels a user can turn up or down. Each record carries when and where it was written. Records go to the standard error, or anywhere the program chooses.
Its users:
- the build tool and the self-hosted compiler, saying what they run and how long it takes;
- the language server,
sakura lsp, whose records go to the client aswindow/logMessage, since its standard output belongs to the protocol; - programs whose records other programs read, as JSON lines.
Probed:
- On 2026-10-07, in the scratchpad (
logprobe/): the clocks, whichstd::sysnow has; whether a handle is a terminal, through theTCGETSioctl; and a floor,call_site()as a default, and a sink held in a module's variable. - On 2026-10-20, in the scratchpad (
plans/logging/): in the VM, as executables at-O0and-O2, withrun --checks, and checked for Windows, with 0 notes and 0 warnings. A sketch ofstd::login a copy of std covered:sys::is_terminal, added to a copy ofstd::sys: false through a pipe, and true under a pseudo-terminal;- the floor,
log::towith owned and borrowed sinks and nested guards, and the text and JSON sinks; - 400 records from four threads, all counted;
math::logbesidelog::info, and the "Using it" program below.
What's there now
io::error_output(), the shared writer of the standard error, which writes at once.io::error_output_locked()holds it for one thread across several writes, asprintandprintlnhold the standard output for each call.call_site(), which, as a default, is filled in with where the call is written: its file, line, column, and the function's signature, while compiling.- Interpolation, which formats any value: enums by their member's name, and structs field by field.
- The clocks and the calendar:
sys::clock(clock_kind::wall)andsteady, and instd::time,timestamp::now(),timestamp::at(zone), which gives thedate_timea zone's clocks show, andrfc3339(). That writes as many places of a second as the moment has:.372006452,.45, or none for a whole second. - No way to tell whether a stream is a terminal:
std::syshas only a privateis_consoleon Windows. - Threads:
std::thread'smutex, andatomic<T>, so several threads may log at once. A signal handler runs in the thread the program began with, at a safe point, and std's own code has none. io::writer_of(stream), which owns a stream given by value, asmove(f), and borrows one given as&mut f.- Owning a value whatever its type:
function<S>owns any callable of a signature through a table of what its type does, andsys::handlekeeps each handler in one until another is set. A sink of any type can be owned the same way. json::writer, which writes into a string it keeps,clear()s to write the next value in the same memory, and writes text that isn't UTF-8 onceset_lossy.process::variable(name), which reads the environment.- Programs print with
println, or write toio::error_output()directly. The language server sendswindow/logMessagethrough its ownserver::log.
What it needs
- Levels: trace, debug, info, warning and error, and a floor below which nothing is written.
- Where and when: each record's file, line and function, and the time.
- Cheap when off: a record below the floor costs a load and a comparison.
- Sinks:
- the standard error, by default;
- any
writable, as a file; - a program's own sink, as a language server's.
- Formats: text for people, coloured on a terminal, and JSON lines for programs.
- Order kept with the rest of the output: a record to the standard error is written at once, as other writes to it are, and as one write, so lines don't interleave.
- Threads: records made by several threads at once are each written whole.
How it fits the rules
- One logger, shared, as
io::output()is (decision 2).- Its floor is an
atomic<u8>ofstd::log, read withorder::relaxed, which in an executable is a plain load. - Its sink is behind a
thread::mutex, so records from several threads are written whole, one at a time, and each thread's in the order it made them. - A record made while its own thread holds that lock, by a sink that logs, or by a
signal handler run at a safe point in a program's own sink, is dropped rather
than waited for. A thread holding
io::error_output_locked()logs only after letting go of it, as it may notprintwhile holdingio::output_locked().
- Its floor is an
- A sink is taken as
io::writer_oftakes a stream (decision 4).log::to(sink)owns a sink given by value, and borrows one given as&mut mine. It gives back a guard that puts the previous sink back where it closes, closing one it owns. The guard is@nodiscard, solog::to(&mut mine);on its own, which would put the old sink back at once, is an error (probed). - A record is plain data, made of views. It's valid only while a sink writes it, so a sink keeping one copies what it needs.
- Logging never fails the program.
- A write that fails is dropped. No
resultcomes back fromlog::info, and a sink'swritegivesvoid, where a stream's givesresult<void, io_error>. - Writing to a closed standard error still stops the program quietly, by
SIGPIPE, as any write to the console does (status 141 in the VM and in executables, probed).
- A write that fails is dropped. No
- Calls are written qualified, as
log::info(...). Without the module,infois ambiguous withstd::io::infounderimport std::io;(probed again), anderrorreads asresult's field. The logarithm doesn't clash: underimport std::math;andimport std::log;,log(x)ismath::logandlog::infothe module (probed).
Layers
std::sys gains
| Operation | Does |
|---|---|
is_terminal(handle: fd): bool |
Whether the handle is a terminal. Probed |
allow_colour(handle: fd): bool |
Whether the handle shows colour codes, letting it where it can |
- On Linux:
is_terminalis anioctlwithTCGETS(16 on x86-64), throughsyscall, asclockcallsclock_gettime.allow_colourisis_terminal. - On Windows:
std::sysalready has a privateis_console, which asksGetConsoleMode, andis_terminalgives it the handlehandle_offinds. A console shows colour codes only once its virtual terminal processing is on, soallow_colourturns it on withSetConsoleMode, and is false where that's refused. - The clock is built:
sys::clock(which: clock_kind): i64, ofclock_gettimeon Linux, and ofGetSystemTimePreciseAsFileTimeandQueryPerformanceCounteron Windows.clock_kindis in modulestd, instd/time/clock.sakura. - Records keep a
time::timestamp.std::logwrites its text from thedate_timethattimestamp::at(zone::utc())gives, to the millisecond, so every line's time is one width, whererfc3339()would write as many places as the moment has. The calendar isstd::time's.
std::log (decision 1)
module std::log;
#! How much a record matters, from least to most.
pub enum level: u8 {
trace, #! Each step, for following the program closely.
debug, #! What a developer wants while looking into a problem.
info, #! What the program is doing, at a pace a user follows.
warning, #! Something unexpected that the program went on past.
error, #! Something that failed.
off, #! As a floor, nothing is written.
}
#! What the program said, as a sink is given it.
pub struct record {
pub val level: level; #! How much it matters.
pub val time: time::timestamp; #! When, by the wall clock.
pub val at: site; #! Where it was written: file, line, column, and function.
pub val message: strview; #! What was said, valid only while the sink writes it.
}
#! Where records go.
pub trait sink {
#! Writes a record.
def write(&mut this, entry: &record): void;
#! Writes what it holds back, which a sink holding nothing back leaves as it is.
def flush(&mut this): void {}
}
pub def trace(message: strview, at: site = call_site()): void;
pub def debug(message: strview, at: site = call_site()): void;
pub def info(message: strview, at: site = call_site()): void;
pub def warning(message: strview, at: site = call_site()): void;
pub def error(message: strview, at: site = call_site()): void;
pub def write(wanted: level, message: strview, at: site = call_site()): void;
pub def enabled(wanted: level): bool; # whether a record at the level is written
pub def set_floor(lowest: level): void; # `info` until it's set
pub def floor(): level;
#! Sends records to a sink until the guard closes. One given by value is the
#! logger's, and one given as `&mut mine` is borrowed, as `io::writer_of` takes a
#! stream.
pub def to<K>(target: K): guard where K: sink;
pub def flush(): void;
#! Puts the sink before it back where it closes, closing one the logger owns.
@nodiscard
pub struct guard : owning { ... }
#! How text records are written.
pub struct style {
pub var time: bool = true; #! Whether the time is written.
pub var site: bool = true; #! Whether the file and line are written.
pub var colour: bool = false; #! Whether levels are coloured, for a terminal.
}
#! Writes records as lines of text, to a stream it owns or borrows, as
#! `io::writer_of` does.
pub struct text_sink<S> : sink, owning where S: writable { ... }
pub def text_to<S>(stream: S, how: style = style {}): text_sink<S> where S: writable;
#! Writes each record as a line holding one JSON object.
pub struct json_sink<S> : sink, owning where S: writable { ... }
pub def json_to<S>(stream: S): json_sink<S> where S: writable;
flushhas an empty body, not@optional. The compiler doesn't call an@optionalmethod through a trait reference, which is how the logger reaches its sink, while a default is taken even by a sink that doesn't name the trait (both probed).
Using it
import std;
import std::args;
import std::io;
import std::log;
@command{ help = "Builds things." }
struct options {
@option{ short = 'v', count = true, help = "Says more: -v for debug, -vv for trace." }
var verbose: u8;
@argument{ value = "FILE", help = "The files to build." }
var files: vector<strview>;
}
def main(args: span<strview>): void {
val given := args::parse_or_exit::<options>(args);
log::set_floor(given.verbose >= 2 ? log::level::trace
: given.verbose == 1 ? log::level::debug
: log::level::info);
log::info($"building {given.files.length} files");
if log::enabled(log::level::debug) {
log::debug(list_of(&given.files)); # built only where it's written
}
# Records go to a file instead of the console until `using` closes.
val named := path::parse("build.log") else { return; };
var file := io::file::create(&named) else { return; };
val using := log::to(log::text_to(move(file)));
log::warning("this goes to build.log");
} # `using` closes, closing the sink and the file
A language server sends records to its client, as server::log sends
window/logMessage:
struct client_log : log::sink {
var to: &mut server;
}
def client_log::write(&mut this, entry: &log::record): void {
val kind: u32 = match entry.level { error => 1, warning => 2, info => 3, else => 4 };
this.to.log(kind, entry.message);
}
# In a method of `server`, for as long as it serves:
val using := log::to(client_log { to = this });
How each part works
-
Below the floor:
log::infoand the rest each compare the level with the floor before calling what makes the record. They're small, so-O2inlines them where they're called, and a record below the floor costs a load and a compare, besides its arguments (probed; a test inside the one function they all call wasn't copied out of it).- Its message is still built by the caller, as any argument is. So a message costly
to build is written under
if log::enabled(...)(decision 3).
-
Making a record: the time is read by
time::timestamp::now()only for a record that's written, and the site comes from the default. -
The default sink writes text to the standard error, through
io::error_output_locked()for each record, so it mixes with nothing another thread writes there holding it.- It colours levels where
sys::allow_colour(sys::fd::stderr)holds, asked once. - It holds nothing of its own, so there's nothing to close.
- It colours levels where
-
Text: one line per record, made in a
string, then written as one write.2026-10-07T12:42:03.451Z INFO main.sakura:16 building 12 files 2026-10-07T12:42:03.517Z WARN plan.sakura:88 `old.sakura` is listed twice- The time is RFC 3339 in UTC, to the millisecond, always three places. A time
before 1970 is floored, as
std::timefloors it: 995 milliseconds before 1970 is1969-12-31T23:59:59.005Z(probed). - Levels are padded to five, as
TRACE,DEBUG,INFO,WARNandERROR. - The path is as the compiler was given it.
- With
colour,TRACEandDEBUGare dim,WARNis yellow andERRORred. - A message holding line breaks is written as it is, so its later lines begin with nothing before them.
- The time is RFC 3339 in UTC, to the millisecond, always three places. A time
before 1970 is floored, as
-
JSON: one object per line, written through a
json::writerthe sink keeps, cleared for each record, so the message is escaped. The writer is lossy, so a message that isn't UTF-8 is written with U+FFFD where it breaks, rather than asnull. The level is its member's name, as interpolation writes it:{"time":"2026-10-07T12:42:03.451Z","level":"info","file":"main.sakura","line":16,"function":"def main(args: span<strview>): void","message":"building 12 files"} -
log::tomoves the sink it's given to the heap, asfunctionholds a callable too large for itself, keeps a&mut sinkto it, and gives a guard holding the one before. Given&mut mine, what it moves is only the reference.- Guards closed in the reverse of the order they were made, as RAII closes them, put back each sink in turn, holding the lock, so a record being written on another thread is finished first.
- A guard then closes the sink it set where the logger owns it, which flushes what the sink holds back.
-
log::flushflushes the sink, where it flushes. A program stopping throughsys::exitflushes nothing and closes nothing, guards included, as now (probed), so a sink that holds records back is flushed first. The logger's own variables are never closed, as no module's are when the program ends.
Testing
-
test/std/log.sakura, written withstd::testing, covers:- the floor: each level against each floor,
off, andenabled; - sites: the file and line a record gives are where
log::infowas written; - sinks:
- a program's own sink collecting records, owned and borrowed;
log::toguards, nested, putting each sink back as they close, and closing those the logger owns;log::flushreaching a sink that flushes, and one that doesn't;
- text: records with a fixed time written by
text_to(&mut text)into astring, compared exactly, with and without the time, the site and colour; - times: always three places, as
.000and.450, and a time before 1970. Dates themselves arestd::time's, tested intest/std/time.sakura; - JSON: each line read back with
json::parse, including a message with quotes and line breaks, and one that isn't UTF-8; - threads: several threads logging at once into one sink, every record whole and counted;
- a sink that logs, whose record is dropped rather than waited for.
Each test runs in a copy of the program, so a floor or sink one sets is gone for the next.
- the floor: each level against each floor,
-
In the corpus,
test/programs: records toio::output()betweenprintlns, written in the order they were made, and records to the standard error beside them, with the time left out. -
Where they run: in the VM, as executables at
-O0and-O2, and withrun --checks. The compiler must check them with 0 notes and 0 warnings.
Phases
About 30 lines of std::sys, 450 of std::log, and 300 of tests, and no change to the
compiler. The sketch probed was 200 lines of code without its documentation. Each phase
ends with its tests passing.
sys::is_terminalandsys::allow_colour, for Linux and Windows on x86-64.sys::clockis built.std::log: levels, records, the floor,sink,log::toand its guard, the lock, and the text sink, with the default sink over the standard error.- The JSON sink.
- A "Logging" part of the README's standard library section, and
std::login its table of modules.
Later, where wanted
- Fields: pairs of names and values that the JSON sink writes as members, as in
log::info("served", log::field("path", p), log::field("ms", ms)). - Named loggers, one for each part of a program, each with its own floor.
- The floor from the environment, as
SAKURA_LOG=debug, andNO_COLOR.process::variableexists now, so this waits only on choosing the names. - Several sinks at once, as a sink that writes to two others.
- A sink on a thread of its own, handed records through a
thread::channel, so a slow sink doesn't hold up the threads logging. It would copy each record's message, since a record's views last only while it's written. - A sink to
syslog, or to the systemd journal.
Durations and dates as types, with the time zone from the system, were on this list.
std::time has them now.
Decisions for you
- Where it lives:
- (a)
std::log, instd/log/(recommended). Calls read aslog::info(...). - (b)
std::logging. It was to leave the namelogfree for a logarithm, butstd::mathhaslognow, and it lives beside a modulelog(probed). So it's only a longer name.
- (a)
- The logger:
- (a) One, shared, as
io::output()is (recommended). Any function can log without being given anything. Threads logging at once wait on its lock for each record written. - (b) Logger values given to what logs. That's explicit and easy to test, and a value one thread holds needs no lock, but every function that logs needs a parameter.
- (a) One, shared, as
- Messages below the floor:
- (a) Built anyway, with
log::enabledfor messages costly to build (recommended). Interpolating a few values costs little next to what a program does between records. - (b) Also overloads taking a function that builds the message, as
log::debug(def() => describe(&plan)). It's shorter at the call, and the closure costs only its two words now, since closures refer to what they use rather than own it. But the compiler calls a lambda written in place ambiguous betweendebug(strview)anddebug(def(): string), typed or not (probed 2026-10-20). A function value named first works. - (c) Records below a floor the build sets are removed while compiling. That
needs a new
whenkey, aslog >= debug, and a compiler option to set it.
- (a) Built anyway, with
- How a sink is held:
- (a) As
io::writer_ofholds a stream, until its guard closes (recommended).log::toowns a sink given by value, and borrows one given as&mut mine. The guard keeps a borrowed sink from outliving it, and closes an owned one, flushing what it holds back. Both were probed. - (b) Owned until another is set, with no guard, as
sys::handlekeeps a handler in afunctionuntil another handles the signal. It's one call for the whole run, but nothing puts the old sink back, and nothing closes the logger as the program ends, so a sink holding records back loses them unless the program flushes first. - (c) Borrowed only, until its guard closes, as
log::to(&mut mine). This was the recommendation of 2026-10-07, before std owned values of any type, asfunctiondoes. It makes a program declare its sink before the guard, or the sink closes first.
- (a) As
- The time a record gives:
- (a) The wall clock, in UTC, written as RFC 3339 to the millisecond (recommended).
- (b) The wall clock in the local zone, with its offset, from
timestamp::at(zone::local()). That's what a person nearby reads, but records from machines in other zones, or from either side of a change of the clocks, don't sort as text. - (c) Time since the program started, from the steady clock, as an
instant'selapsed(). That's easier to read in a short run, but means nothing next to another program's records. - (d) None unless a style asks for it.