Standard library · System and tools

log

Recording what a program does, with levels, a prefix, structured fields, JSON output and writing to a file.

import log

For a program running on a server, println is not enough: you need to know how important each message is and when it was written, and to be able to silence the unimportant ones. The log package has four levels, debug, info, warn and error, and records only the messages at or above the level you set; the default level is info. Each line goes out in plain text or as one JSON object, to standard error, standard output or a file that can rotate.

A text line looks like 2026-10-17 13:09:22 [INFO] shop order 1042 accepted: the local time, the level, the prefix and the message. The examples below turn the time off with ShowTime(false) so their output is stable.

All settings are global to the program: call SetLevel, SetFormat, SetPrefix and one of ToStderr, ToStdout or ToFile once near the start of main, and every package that imports log writes the same way. For a quick look at a value while you work on the code, debug is the better tool; for timing and memory figures, runtime.

The things people get wrong:

  • A file log is buffered. Lines reach the disk when the buffer fills or at CloseFile, so tail -f lags behind and a crash loses the last lines. Call CloseFile on every way out of the program.
  • The text format writes the message as it is. A value from a user that holds a line break starts a fake log line; use JSON, which escapes it (see below).
  • The settings are plain globals with no lock. Change them at startup only, not while other threads are logging.
  • The time is local time with no zone offset, also in JSON. Run servers with TZ=UTC when logs from several machines are compared.

Choose the level from the settings

The level should not be fixed in the code. During development you want debug messages; on a busy server you want warnings and errors only. Read the level as text from a settings file or the environment and turn it into a number with ParseLevel. It accepts debug, info, warn, warning and error in any case, and falls back to info for anything else, so a typo never silences the log completely.

log-level-config.salam
import log
import config

func setup(text: str):
    mut c := config.ParseEnv(text)
    defer config.Free(c)
    level := log.ParseLevel(config.GetOr(c, "LOG_LEVEL", "info"))
    log.SetLevel(level)
    log.SetPrefix(config.GetOr(c, "APP_NAME", "app"))
    println "-- level", log.LevelName(log.GetLevel())
end

func work():
    log.Debug("cache lookup for key user:7")
    log.Info("order 1042 accepted")
    log.Warn("payment provider answered slowly")
    log.Error("could not send the receipt email")
end

func main:
    log.ToStdout()
    log.ShowTime(false)
    setup("LOG_LEVEL=debug\nAPP_NAME=shop\n")
    work()
    setup("LOG_LEVEL=warning\nAPP_NAME=shop\n")
    work()
    setup("LOG_LEVEL=loud\n")
    work()
end
Output-- level DEBUG [DEBUG] shop cache lookup for key user:7 [INFO] shop order 1042 accepted [WARN] shop payment provider answered slowly [ERROR] shop could not send the receipt email -- level WARN [WARN] shop payment provider answered slowly [ERROR] shop could not send the receipt email -- level INFO [INFO] app order 1042 accepted [WARN] app payment provider answered slowly [ERROR] app could not send the receipt email

The config package used here is described on its own page, config. The prefix is a good place for the program's name, so that lines from several programs in one log stay apart.

JSON logs for a log collector

Text lines are easy to read; JSON lines are easy for tools such as Loki, Elasticsearch or a cloud log service to search. SetFormat(FormatJSON) turns every line into one JSON object with level, the optional prefix, msg, and one member for each key given to the ...KV functions. With the time switched on, a time member in ISO 8601 comes first.

log-json-requests.salam
import log
import str

struct Request:
    pub method: str = ""
    pub path: str = ""
    pub status: int = 0
    pub ms: int = 0
end

func record(r: Request):
    mut keys := Vector {} as Vector<str>
    mut vals := Vector {} as Vector<str>
    defer keys.Free()
    defer vals.Free()
    keys.Push("method")
    vals.Push(r.method)
    keys.Push("path")
    vals.Push(r.path)
    keys.Push("status")
    vals.Push(str.FromInt(r.status as i64))
    keys.Push("ms")
    vals.Push(str.FromInt(r.ms as i64))
    if r.status >= 500:
        log.ErrorKV("request failed", keys, vals)
    else r.status >= 400:
        log.WarnKV("request rejected", keys, vals)
    else:
        log.InfoKV("request served", keys, vals)
    end
end

func main:
    log.ToStdout()
    log.ShowTime(false)
    log.SetFormat(log.FormatJSON)
    log.SetPrefix("api")
    record(Request { method = "GET", path = "/products", status = 200, ms = 12 })
    record(Request { method = "POST", path = "/login", status = 401, ms = 3 })
    record(Request { method = "GET", path = "/report \"q3\"", status = 503, ms = 950 })
end
Output{"level": "INFO", "prefix": "api", "msg": "request served", "method": "GET", "path": "/products", "status": "200", "ms": "12"} {"level": "WARN", "prefix": "api", "msg": "request rejected", "method": "POST", "path": "/login", "status": "401", "ms": "3"} {"level": "ERROR", "prefix": "api", "msg": "request failed", "method": "GET", "path": "/report \"q3\"", "status": "503", "ms": "950"}

Picking the level from the result, error for a 5xx answer and warn for a 4xx one, lets you alert on errors without reading every request. Quotes inside a value are escaped, so each line stays valid JSON. All values are written as JSON strings, numbers included.

Log to a file that does not grow forever

ToFile appends to a file and returns 0, or minus one when the file cannot be opened. SetRotation(max_bytes, max_backups) keeps it in check: when the file has reached max_bytes, the next line first renames it to .1, shifts the older copies up by one and starts a new, empty file. Copies past max_backups are deleted.

log-rotation.salam
import log
import os
import io
import str

func first_line(path: str): str:
    lines := io.ReadFile(path).Split("\n")
    defer lines.Free()
    ret lines.Get(0)
end

func main:
    files := ["worker.log", "worker.log.1", "worker.log.2", "worker.log.3"]
    each f in files:
        os.Remove(f)
    end
    log.ShowTime(false)
    if log.ToFile("worker.log") != 0:
        println "cannot open worker.log"
        ret 1
    end
    log.SetRotation(120, 2)
    repeat 24 in i:
        log.Info("processed job " + str.FromInt(i as i64))
    end
    log.CloseFile()
    each f in files:
        if os.Exists(f):
            println f, "starts with", first_line(f)
        else:
            println f, "does not exist"
        end
    end
end
Outputworker.log starts with [INFO] processed job 22 worker.log.1 starts with [INFO] processed job 17 worker.log.2 starts with [INFO] processed job 12 worker.log.3 does not exist

The limit here is tiny so that the example rotates a few times. A real service uses something like 10 * 1024 * 1024 bytes and five backups. The size is checked before each line is written, so a file can end up one line longer than the limit. Call CloseFile before the program ends, or the last lines stay in the buffer; Fatal closes the file for you before it exits with status 1.

Key and value fields in text logs

For text logs, Field, FieldInt and FieldBool build key=value pieces and KV joins them after a message. Field puts quotes around a value that contains a space or a quote, and escapes the quotes inside, so a line can still be split into fields by a program.

log-fields.salam
import log

func login_line(user: str, attempts: i64, ok: bool, agent: str): str:
    mut fields := Vector {} as Vector<str>
    defer fields.Free()
    fields.Push(log.Field("user", user))
    fields.Push(log.FieldInt("attempts", attempts))
    fields.Push(log.FieldBool("ok", ok))
    fields.Push(log.Field("agent", agent))
    ret log.KV("login", fields)
end

func main:
    log.ToStdout()
    log.ShowTime(false)
    log.Info(login_line("sara", 1, true, "curl/8.5"))
    log.Warn(login_line("guest user", 3, false, "my \"test\" bot"))
    println log.Field("empty", "")
    println log.Field("path", "/a b")
end
Output[INFO] login user=sara attempts=1 ok=true agent=curl/8.5 [WARN] login user="guest user" attempts=3 ok=false agent="my \"test\" bot" empty= path="/a b"

An empty value is written as key= with nothing after it. Only spaces and quotes trigger the quoting: a tab, a backslash or a line break goes through unchanged. These helpers only build text; the level filter still applies when you pass the result to Info or Warn.

Formatted messages and values from users

Infof and the other ...f functions fill each {} with the next string from a vector, which reads better than a chain of +. They do not clean the values. Here a user name with a line break forges an [ERROR] line in the text log, while the JSON line keeps it inside one string as \n.

log-untrusted.salam
import log

func pair(a: str, b: str): Vector<str>:
    mut v := Vector {} as Vector<str>
    v.Push(a)
    v.Push(b)
    ret v
end

func main:
    log.ToStdout()
    log.ShowTime(false)
    name := "mina\n[ERROR] disk full"
    args := pair(name, "10.0.0.7")
    defer args.Free()
    log.Infof("user {} signed in from {}", args)
    keys := pair("user", "ip")
    defer keys.Free()
    log.SetFormat(log.FormatJSON)
    log.InfoKV("user signed in", keys, args)
    log.SetFormat(log.FormatText)
    log.SetLevel(log.LevelError + 1)
    log.Error("nobody sees this")
    log.SetLevel(log.LevelInfo)
    log.Info("logging is back on")
end
Output[INFO] user mina [ERROR] disk full signed in from 10.0.0.7 {"level": "INFO", "msg": "user signed in", "user": "mina\n[ERROR] disk full", "ip": "10.0.0.7"} [INFO] logging is back on

The end of the example shows a trick for tests and quiet tools: a level above LevelError silences everything, and setting it back turns logging on again.

Log from many threads without blocking

The sink writes are serialized, so several threads can call the log functions at once without mixing characters. For a hot path, go one step further: StartAsync(capacity) starts one writer thread and a channel of the given capacity. Each call then formats its line and hands it to the channel; when the channel is full the caller waits, which is the back pressure that keeps memory bounded. The writer drains the channel in order, so lines from one thread keep their order and lines from different threads interleave only between whole messages.

log-Async.salam
import log

func main:
    log.ShowTime(false)
    log.ToStdout()
    log.SetPrefix("async")

    started := log.StartAsync(4 as i64)
    log.Info("one")
    log.Info("two")
    log.Flush()
    log.StopAsync()

    println "started:", started
end
Output[INFO] async one [INFO] async two started: true

StartAsync returns false when asynchronous mode is already on; the second call does not start another writer. Flush waits until every line emitted so far has reached the sink, and StopAsync stops the writer after draining the queue and then frees it. A zero capacity makes the queue a rendezvous, so each call waits for the writer to take its line. Fatal flushes before it exits.

Configure the level, prefix, format and sink before starting the writer; they are still plain globals and are not meant to change while other threads are logging. If StopAsync is never called, the writer stays until the process exits; lines already flushed are safe, but the last queued lines may be lost on a crash, exactly like a buffered file.

Which function for which job

You wantUse
A plain messageDebug, Info, Warn, Error
A message with values filled inInfof and the other ...f functions, with {} placeholders
Fields that tools can searchInfoKV and the other ...KV functions, best with FormatJSON
The level as a variableLog(level, msg)
Stop the program after an unrecoverable errorFatal
Output for a container or systemdthe default, ToStderr

Constants and variables

LevelDebug

const LevelDebug: i32 = 0
The debug level: detail for whoever is working on the code.
log-Info.salam
import log

func main:
    log.ToStdout()
    log.ShowTime(false)
    log.SetPrefix("[app]")
    log.Debug("this is not shown")
    log.Info("the server is ready")
    log.Warn("memory is running low")
    log.Error("the connection dropped")
    log.SetLevel(log.LevelDebug)
    log.Debug("now it is shown")
    log.Log(log.LevelWarn, "at a level of my choosing")
    println log.GetLevel(), log.LevelName(log.LevelError), log.ParseLevel("warn"), log.LevelInfo
end
Output[INFO] [app] the server is ready [WARN] [app] memory is running low [ERROR] [app] the connection dropped [DEBUG] [app] now it is shown [WARN] [app] at a level of my choosing 0 ERROR 2 1

LevelInfo

const LevelInfo: i32 = 1
The info level: ordinary events.

The example for this item is shown with the ones above: log-Info.salam

LevelWarn

const LevelWarn: i32 = 2
The warn level: something unusual, but not an error.

The example for this item is shown with the ones above: log-Info.salam

LevelError

const LevelError: i32 = 3
The error level.

The example for this item is shown with the ones above: log-Info.salam

FormatText

const FormatText: i32 = 0
The readable text format.
log-InfoKV.salam
import log

func main:
    log.ToStdout()
    log.ShowTime(false)
    mut keys := Vector {} as Vector<str>
    mut values := Vector {} as Vector<str>
    defer keys.Free()
    defer values.Free()
    keys.Push("user")
    values.Push("sara")
    keys.Push("ms")
    values.Push("42")
    log.InfoKV("request served", keys, values)
    log.WarnKV("it was slow", keys, values)
    log.ErrorKV("it failed", keys, values)
    log.SetLevel(log.LevelDebug)
    log.DebugKV("the details", keys, values)
    log.SetFormat(log.FormatJSON)
    log.Info("as JSON")
    println log.GetFormat() == log.FormatJSON, log.FormatText
    mut fields := Vector {} as Vector<str>
    defer fields.Free()
    fields.Push(log.Field("path", "/login"))
    fields.Push(log.FieldInt("status", 200))
    fields.Push(log.FieldBool("cached", false))
    println log.KV("response", fields)
end
Output[INFO] request served user=sara ms=42 [WARN] it was slow user=sara ms=42 [ERROR] it failed user=sara ms=42 [DEBUG] the details user=sara ms=42 {"level": "INFO", "msg": "as JSON"} true 0 response path=/login status=200 cached=false

FormatJSON

const FormatJSON: i32 = 1
The JSON format, one object per line, for log collectors.

The example for this item is shown with the ones above: log-InfoKV.salam

Functions

LevelName

func LevelName(l: int): str
The upper case name of a level: DEBUG, INFO, WARN or ERROR. Anything below 0 counts as debug and anything above 3 as error.

The example for this item is shown with the ones above: log-Info.salam

ParseLevel

func ParseLevel(s: str): int
Turns text such as "warn" into a level, ignoring case and surrounding spaces. It knows debug, info, warn, warning and error, and gives info for anything else.

The example for this item is shown with the ones above: log-Info.salam

SetLevel

func SetLevel(l: int)
The lowest level that is recorded. LevelError + 1 silences the log.

The example for this item is shown with the ones above: log-Info.salam

GetLevel

func GetLevel(): int
The current level.

The example for this item is shown with the ones above: log-Info.salam

SetPrefix

func SetPrefix(p: str)
A prefix that comes after the level on every message, such as the program name; in JSON it is the prefix member. An empty string removes it.

The example for this item is shown with the ones above: log-Info.salam

ShowTime

func ShowTime(b: bool)
Whether to start each message with the local time, to the second. On by default.

The example for this item is shown with the ones above: log-Info.salam

SetFormat

func SetFormat(f: int)
The text or JSON format.

The example for this item is shown with the ones above: log-InfoKV.salam

GetFormat

func GetFormat(): int
The current format.

The example for this item is shown with the ones above: log-InfoKV.salam

SetRotation

func SetRotation(max_bytes: i64, max_backups: int)
For a file log: once the file has reached max_bytes, the next line renames it to .1, moves older copies up and starts a new file, keeping at most max_backups old copies. 0 bytes turns rotation off.
log-ToFile.salam
import log
import io

func main:
    log.ShowTime(false)
    println log.ToFile("app.log")
    log.SetRotation(1024 * 1024, 3)
    log.Info("written to the file")
    log.CloseFile()
    log.ToStderr()
    print io.ReadFile("app.log")
end
Output0 [INFO] written to the file

ToStderr

func ToStderr()
Write the log to standard error, which is the default.

The example for this item is shown with the ones above: log-ToFile.salam

ToStdout

func ToStdout()
Write the log to standard output.

The example for this item is shown with the ones above: log-Info.salam

ToFile

func ToFile(path: str): int
Appends the log to a file and returns 0, or minus one when it cannot be opened. Writes are buffered until CloseFile.

The example for this item is shown with the ones above: log-ToFile.salam

CloseFile

func CloseFile()
Flushes and closes the log file and sends the log back to standard error.

The example for this item is shown with the ones above: log-ToFile.salam

StartAsync

func StartAsync(capacity: i64): bool
Starts a background writer thread and a channel queue of the given capacity; every log call then enqueues its line and returns without touching the sink. A full queue makes the caller wait. Returns false when asynchronous mode is already on. Zero means an unbuffered handoff.
log-Async.salam
import log

func main:
    log.ShowTime(false)
    log.ToStdout()
    log.SetPrefix("async")

    started := log.StartAsync(4 as i64)
    log.Info("one")
    log.Info("two")
    log.Flush()
    log.StopAsync()

    println "started:", started
end
Output[INFO] async one [INFO] async two started: true

StopAsync

func StopAsync()
Stops asynchronous mode after draining the queue: closes the channel, joins the writer and frees it. Does nothing when asynchronous mode is off.

The example for this item is shown with the ones above: log-Async.salam

Flush

func Flush()
Waits until every line emitted so far has been written to the sink. Lines emitted after the call are not covered; it returns immediately when asynchronous mode is off.

The example for this item is shown with the ones above: log-Async.salam

IsAsync

func IsAsync(): bool
Whether asynchronous mode is on.

The example for this item is shown with the ones above: log-Async.salam

Log

func Log(l: int, msg: str)
Records a message at the level you choose.

The example for this item is shown with the ones above: log-Info.salam

Debug

func Debug(msg: str)
A debug message.

The example for this item is shown with the ones above: log-Info.salam

Info

func Info(msg: str)
An info message.

The example for this item is shown with the ones above: log-Info.salam

Warn

func Warn(msg: str)
A warning.

The example for this item is shown with the ones above: log-Info.salam

Error

func Error(msg: str)
An error message.

The example for this item is shown with the ones above: log-Info.salam

Debugf

func Debugf(tmpl: str, args: Vector<str>)
A formatted debug message: every {} is filled with the next string from args.
log-Infof.salam
import log

func main:
    log.ToStdout()
    log.ShowTime(false)
    mut args := Vector {} as Vector<str>
    defer args.Free()
    args.Push("Sara")
    args.Push("3")
    log.Infof("user {} signed in and has {} messages", args)
    log.Warnf("a failed attempt for {}", args)
    log.Errorf("user {} was blocked", args)
    log.SetLevel(log.LevelDebug)
    log.Debugf("id {}", args)
end
Output[INFO] user Sara signed in and has 3 messages [WARN] a failed attempt for Sara [ERROR] user Sara was blocked [DEBUG] id Sara

Infof

func Infof(tmpl: str, args: Vector<str>)
A formatted info message.

The example for this item is shown with the ones above: log-Infof.salam

Warnf

func Warnf(tmpl: str, args: Vector<str>)
A formatted warning.

The example for this item is shown with the ones above: log-Infof.salam

Errorf

func Errorf(tmpl: str, args: Vector<str>)
A formatted error message.

The example for this item is shown with the ones above: log-Infof.salam

Fatal

func Fatal(msg: str)
Records an error message, closes the log file and ends the program with code 1, without running defer. Its example is not run here.
log-Fatal.salam
import log

func main:
    log.Fatal("the configuration file was not found")
end

Field

func Field(key: str, val: str): str
Builds one key=value field, with quotes around a value that has a space or a quote.

The example for this item is shown with the ones above: log-InfoKV.salam

FieldInt

func FieldInt(key: str, val: i64): str
A field with a numeric value.

The example for this item is shown with the ones above: log-InfoKV.salam

FieldBool

func FieldBool(key: str, val: bool): str
A field with a boolean value.

The example for this item is shown with the ones above: log-InfoKV.salam

KV

func KV(msg: str, fields: Vector<str>): str
Joins a message and its fields with spaces, for passing to Info and the others.

The example for this item is shown with the ones above: log-InfoKV.salam

DebugKV

func DebugKV(msg: str, keys: Vector<str>, vals: Vector<str>)
A debug message with key and value fields.

The example for this item is shown with the ones above: log-InfoKV.salam

InfoKV

func InfoKV(msg: str, keys: Vector<str>, vals: Vector<str>)
An info message with fields from two vectors of the same length, keys and values. In JSON each pair becomes a member, always as a string.

The example for this item is shown with the ones above: log-InfoKV.salam

WarnKV

func WarnKV(msg: str, keys: Vector<str>, vals: Vector<str>)
A warning with fields.

The example for this item is shown with the ones above: log-InfoKV.salam

ErrorKV

func ErrorKV(msg: str, keys: Vector<str>, vals: Vector<str>)
An error message with fields.

The example for this item is shown with the ones above: log-InfoKV.salam