Files
2026-11-19 04:54:17 -06:00

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 as window/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, which std::sys now has; whether a handle is a terminal, through the TCGETS ioctl; 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 -O0 and -O2, with run --checks, and checked for Windows, with 0 notes and 0 warnings. A sketch of std::log in a copy of std covered:
    • sys::is_terminal, added to a copy of std::sys: false through a pipe, and true under a pseudo-terminal;
    • the floor, log::to with owned and borrowed sinks and nested guards, and the text and JSON sinks;
    • 400 records from four threads, all counted;
    • math::log beside log::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, as print and println hold 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) and steady, and in std::time, timestamp::now(), timestamp::at(zone), which gives the date_time a zone's clocks show, and rfc3339(). 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::sys has only a private is_console on Windows.
  • Threads: std::thread's mutex, and atomic<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, as move(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, and sys::handle keeps 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 once set_lossy.
  • process::variable(name), which reads the environment.
  • Programs print with println, or write to io::error_output() directly. The language server sends window/logMessage through its own server::log.

What it needs

  1. Levels: trace, debug, info, warning and error, and a floor below which nothing is written.
  2. Where and when: each record's file, line and function, and the time.
  3. Cheap when off: a record below the floor costs a load and a comparison.
  4. Sinks:
    • the standard error, by default;
    • any writable, as a file;
    • a program's own sink, as a language server's.
  5. Formats: text for people, coloured on a terminal, and JSON lines for programs.
  6. 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.
  7. 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> of std::log, read with order::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 not print while holding io::output_locked().
  • A sink is taken as io::writer_of takes 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, so log::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 result comes back from log::info, and a sink's write gives void, where a stream's gives result<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).
  • Calls are written qualified, as log::info(...). Without the module, info is ambiguous with std::io::info under import std::io; (probed again), and error reads as result's field. The logarithm doesn't clash: under import std::math; and import std::log;, log(x) is math::log and log::info the 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_terminal is an ioctl with TCGETS (16 on x86-64), through syscall, as clock calls clock_gettime. allow_colour is is_terminal.
  • On Windows: std::sys already has a private is_console, which asks GetConsoleMode, and is_terminal gives it the handle handle_of finds. A console shows colour codes only once its virtual terminal processing is on, so allow_colour turns it on with SetConsoleMode, and is false where that's refused.
  • The clock is built: sys::clock(which: clock_kind): i64, of clock_gettime on Linux, and of GetSystemTimePreciseAsFileTime and QueryPerformanceCounter on Windows. clock_kind is in module std, in std/time/clock.sakura.
  • Records keep a time::timestamp. std::log writes its text from the date_time that timestamp::at(zone::utc()) gives, to the millisecond, so every line's time is one width, where rfc3339() would write as many places as the moment has. The calendar is std::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;
  • flush has an empty body, not @optional. The compiler doesn't call an @optional method 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::info and the rest each compare the level with the floor before calling what makes the record. They're small, so -O2 inlines 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.
  • 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::time floors it: 995 milliseconds before 1970 is 1969-12-31T23:59:59.005Z (probed).
    • Levels are padded to five, as TRACE, DEBUG, INFO, WARN and ERROR.
    • The path is as the compiler was given it.
    • With colour, TRACE and DEBUG are dim, WARN is yellow and ERROR red.
    • A message holding line breaks is written as it is, so its later lines begin with nothing before them.
  • JSON: one object per line, written through a json::writer the 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 as null. 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::to moves the sink it's given to the heap, as function holds a callable too large for itself, keeps a &mut sink to 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::flush flushes the sink, where it flushes. A program stopping through sys::exit flushes 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 with std::testing, covers:

    • the floor: each level against each floor, off, and enabled;
    • sites: the file and line a record gives are where log::info was written;
    • sinks:
      • a program's own sink collecting records, owned and borrowed;
      • log::to guards, nested, putting each sink back as they close, and closing those the logger owns;
      • log::flush reaching a sink that flushes, and one that doesn't;
    • text: records with a fixed time written by text_to(&mut text) into a string, compared exactly, with and without the time, the site and colour;
    • times: always three places, as .000 and .450, and a time before 1970. Dates themselves are std::time's, tested in test/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.

  • In the corpus, test/programs: records to io::output() between printlns, 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 -O0 and -O2, and with run --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.

  1. sys::is_terminal and sys::allow_colour, for Linux and Windows on x86-64. sys::clock is built.
  2. std::log: levels, records, the floor, sink, log::to and its guard, the lock, and the text sink, with the default sink over the standard error.
  3. The JSON sink.
  4. A "Logging" part of the README's standard library section, and std::log in 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, and NO_COLOR. process::variable exists 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

  1. Where it lives:
    • (a) std::log, in std/log/ (recommended). Calls read as log::info(...).
    • (b) std::logging. It was to leave the name log free for a logarithm, but std::math has log now, and it lives beside a module log (probed). So it's only a longer name.
  2. 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.
  3. Messages below the floor:
    • (a) Built anyway, with log::enabled for 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 between debug(strview) and debug(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 when key, as log >= debug, and a compiler option to set it.
  4. How a sink is held:
    • (a) As io::writer_of holds a stream, until its guard closes (recommended). log::to owns 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::handle keeps a handler in a function until 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, as function does. It makes a program declare its sink before the guard, or the sink closes first.
  5. 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's elapsed(). 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.