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.
-- 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.
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
importstrfuncfirst_line(path: str): str:
lines := io.ReadFile(path).Split("\n")
defer lines.Free()
ret lines.Get(0)
endfuncmain:
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"ret1end
log.SetRotation(120, 2)
repeat24in i:
log.Info("processed job " + str.FromInt(i asi64))
end
log.CloseFile()
each f in files:
if os.Exists(f):
println f, "starts with", first_line(f)
else:
println f, "does not exist"endendend
Output
worker.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.
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
funcpair(a: str, b: str): Vector<str>:
mut v := Vector {} asVector<str>
v.Push(a)
v.Push(b)
ret v
endfuncmain:
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
funcmain:
log.ShowTime(false)
log.ToStdout()
log.SetPrefix("async")
started := log.StartAsync(4asi64)
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 want
Use
A plain message
Debug, Info, Warn, Error
A message with values filled in
Infof and the other ...f functions, with {} placeholders
Fields that tools can search
InfoKV and the other ...KV functions, best with FormatJSON
The debug level: detail for whoever is working on the code.
log-Info.salam
import log
funcmain:
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
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
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
funcmain:
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
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
funcmain:
log.ShowTime(false)
log.ToStdout()
log.SetPrefix("async")
started := log.StartAsync(4asi64)
log.Info("one")
log.Info("two")
log.Flush()
log.StopAsync()
println"started:", started
end
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