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, sotail -flags behind and a crash loses the last lines. CallCloseFileon 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=UTCwhen 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.
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()
endThe 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.
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 })
endPicking 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.
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
endThe 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.
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")
endAn 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.
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")
endThe 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.
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
endStartAsync 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 level as a variable | Log(level, msg) |
| Stop the program after an unrecoverable error | Fatal |
| Output for a container or systemd | the default, ToStderr |
Constants and variables
LevelDebug
const LevelDebug: i32 = 0import 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
endLevelInfo
const LevelInfo: i32 = 1The example for this item is shown with the ones above: log-Info.salam
LevelWarn
const LevelWarn: i32 = 2The example for this item is shown with the ones above: log-Info.salam
LevelError
const LevelError: i32 = 3The example for this item is shown with the ones above: log-Info.salam
FormatText
const FormatText: i32 = 0import 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)
endFormatJSON
const FormatJSON: i32 = 1The example for this item is shown with the ones above: log-InfoKV.salam
Functions
LevelName
func LevelName(l: int): strDEBUG, 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"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)LevelError + 1 silences the log.The example for this item is shown with the ones above: log-Info.salam
GetLevel
func GetLevel(): intThe example for this item is shown with the ones above: log-Info.salam
SetPrefix
func SetPrefix(p: str)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)The example for this item is shown with the ones above: log-Info.salam
SetFormat
func SetFormat(f: int)The example for this item is shown with the ones above: log-InfoKV.salam
GetFormat
func GetFormat(): intThe example for this item is shown with the ones above: log-InfoKV.salam
SetRotation
func SetRotation(max_bytes: i64, max_backups: int)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.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")
endToStderr
func ToStderr()The example for this item is shown with the ones above: log-ToFile.salam
ToStdout
func ToStdout()The example for this item is shown with the ones above: log-Info.salam
ToFile
func ToFile(path: str): intCloseFile.The example for this item is shown with the ones above: log-ToFile.salam
CloseFile
func CloseFile()The example for this item is shown with the ones above: log-ToFile.salam
StartAsync
func StartAsync(capacity: i64): boolimport 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
endStopAsync
func StopAsync()The example for this item is shown with the ones above: log-Async.salam
Flush
func Flush()The example for this item is shown with the ones above: log-Async.salam
IsAsync
func IsAsync(): boolThe example for this item is shown with the ones above: log-Async.salam
Log
func Log(l: int, msg: str)The example for this item is shown with the ones above: log-Info.salam
Debug
func Debug(msg: str)The example for this item is shown with the ones above: log-Info.salam
Info
func Info(msg: str)The example for this item is shown with the ones above: log-Info.salam
Warn
func Warn(msg: str)The example for this item is shown with the ones above: log-Info.salam
Error
func Error(msg: str)The example for this item is shown with the ones above: log-Info.salam
Debugf
func Debugf(tmpl: str, args: Vector<str>){} is filled with the next string from args.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)
endInfof
func Infof(tmpl: str, args: Vector<str>)The example for this item is shown with the ones above: log-Infof.salam
Warnf
func Warnf(tmpl: str, args: Vector<str>)The example for this item is shown with the ones above: log-Infof.salam
Errorf
func Errorf(tmpl: str, args: Vector<str>)The example for this item is shown with the ones above: log-Infof.salam
Fatal
func Fatal(msg: str)defer. Its example is not run here.import log
func main:
log.Fatal("the configuration file was not found")
endField
func Field(key: str, val: str): strkey=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): strThe example for this item is shown with the ones above: log-InfoKV.salam
FieldBool
func FieldBool(key: str, val: bool): strThe example for this item is shown with the ones above: log-InfoKV.salam
KV
func KV(msg: str, fields: Vector<str>): strInfo 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>)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>)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>)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>)The example for this item is shown with the ones above: log-InfoKV.salam