Programming Search⌘K

Conceptcore

Structured logging

Also called logging, log levels, log records, key-value logging, JSON logging, semantic logging.

A structured log writes each event as a record with a level, a message and named fields, such as JSON or key=value pairs, so that a program can filter and search the log.

Applies to
core-languages

Idea

A log is the record that a running program keeps of what it did. A developer reads it after a failure, when the program cannot be stopped in a debugger. An operator reads it to see what a server did last night. A program reads it to count errors and to raise an alert.

A plain log line is text for a human:

order 1042 placed by bob, total $19.99

A program that must find all orders over $10 has to parse this sentence with a regular expression. The next developer who changes the sentence breaks the parser. A structured log writes the same event as a record with named fields:

{"level":"INFO","msg":"order placed","order":1042,"user":"bob","total_cents":1999}
level=INFO msg="order placed" order=1042 user=bob total_cents=1999

The message is a fixed name for the kind of event. The values that change go in fields. A tool can then select msg="order placed" and total_cents > 1000 without a parser for each sentence.3

Each record also has a level, which says how important the event is. The program sets a minimum level, and the logger drops the records below it. A developer can leave debug records in the code and turn them on when a failure needs them.1 3

How it works

Records, loggers, handlers

Most logging libraries have the same parts:

  • The record. One event: a time, a level, a message and a set of key-value pairs. Go's log/slog defines a record in these words.3
  • The logger. The object that the code calls, often with a name such as shop.orders. In Python, the names form a hierarchy: shop.orders is a child of shop. A logger with no level of its own uses the level of its nearest ancestor that has one.1
  • The handler. It receives the records that pass the level check and writes them to a destination: standard output, a file, the system log or a network service.1 3
  • The formatter. It turns a record into bytes: a line of text, key=value pairs or JSON.1

The call site creates the record. The configuration decides where it goes and how it looks. A library logs to a named logger and leaves the configuration to the application.

Levels

A level is a number. A higher number is more severe. The names differ between systems, but the order is the same:

System Levels, from low to high
Syslog (RFC 5424) Debug 7, Informational 6, Notice 5, Warning 4, Error 3, Critical 2, Alert 1, Emergency 0 17
Python logging DEBUG 10, INFO 20, WARNING 30, ERROR 40, CRITICAL 50 1
Go log/slog Debug −4, Info 0, Warn 4, Error 8 3
Java System.Logger TRACE, DEBUG, INFO, WARNING, ERROR 5
java.util.logging FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE 7
.NET LogLevel Trace 0, Debug 1, Information 2, Warning 3, Error 4, Critical 5 11
Rust log trace, debug, info, warn, error 12

Syslog numbers the levels in the other direction: 0 is the most severe.17 Go leaves a gap of 4 between its levels, so that other schemes can map named levels between them. Info is 0, the zero value of an integer, so it is the default.3

A level check must be cheap, because a program calls the logger often and drops most records. Python formats the message only when a handler will write the record. The arguments of the call are still computed first.2 Go's documentation gives the same warning: "The arguments to a log call are always evaluated, even if the log event is discarded."3

Fields

A field has a name and a value. The libraries add fields in three ways:

  • At the call. Go takes pairs after the message: log.Info("order placed", "order", 1042).3 Python takes a dictionary in extra=, which becomes attributes of the record.1 .NET takes a message template such as "Order {OrderId} placed", and the names in braces become field names.11
  • On a child logger. Go's Logger.With("request", id) returns a logger that adds the field to every record.3 Python's LoggerAdapter does the same.1 All records of one request can then be found by its id.
  • From the value. In Go, a type with a LogValue method decides how it appears in a record. The documentation suggests this to redact a password.3

Formats

A structured format must keep each record on one line and each value inside its field. JSON escapes a newline in a string as \n and a quote as \". A key=value format must quote a value that has a space and escape the quotes and newlines in it. RFC 5424 defines a format for syslog. A message can carry STRUCTURED-DATA elements, each with an id and named parameters, and the characters ", \ and ] must be escaped in a value:17

[exampleSDID@32473 iut="3" eventSource="Application" eventID="1011"]

In languages

LanguageVerdictNote
PythonStandard library
C++Idiom
JavaStandard library
CIdiom
C#Library
JavaScriptIdiom
TypeScriptIdiom
GoStandard library
RustLibrary
KotlinStandard libraryKotlin's own standard library has no logger, but on the JVM a Kotlin program calls System.Logger and java.util.logging of the JDK, as in the Java example; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyA query does not write log records; the database server keeps its own logs.
BashIdiomPrintf writes a record with key=value pairs to standard error; the shell has no levels and no escaping of values. Alternative: The logger command sends a message to the system log on systems that have one.
PowerShellIdiomWrite-Debug, Write-Verbose, Write-Information, Write-Warning and Write-Error write to separate streams, which act as levels; a record with fields is a hashtable converted with ConvertTo-Json; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup cannot write a record.
CSSDoes not applyA style sheet cannot write a record.
Regular expressionsDoes not applyA pattern cannot write a record, although patterns often parse log lines.
Language Verdict Form
Python stdlib logging: levels, named loggers, handlers, formatters; extra= for fields; JSON needs a small Formatter
Go stdlib log/slog: key-value pairs, JSONHandler and TextHandler, With, LogValuer
Java stdlib System.Logger and java.util.logging; no key-value pairs, so fields go in the message
C# library ILogger in Microsoft.Extensions.Logging, with message templates; System.Text.Json for a hand-made record
Rust library the log facade with a logger crate; {:?} quotes and escapes a value
JavaScript idiom console.log with JSON.stringify
TypeScript idiom as JavaScript, with a union type for the levels
C idiom fprintf and a function that escapes values; syslog() on POSIX systems with the XSI option
C++ idiom std::print with {:?} and std::source_location
Kotlin stdlib the JDK's System.Logger and java.util.logging on the JVM
Bash idiom printf to standard error; the logger command for the system log
PowerShell idiom the Debug, Verbose, Warning and Error streams; ConvertTo-Json for a record
SQL, Regex, HTML, CSS n/a the language does not write log records

Python

The logging module has five named levels with the numbers 10 to 50.1 The root logger has the level WARNING by default, so a program that calls logging.info without any configuration sees nothing.2 The module has no JSON formatter. The example subclasses Formatter and reads the fields that extra= put on the record. log.exception logs at ERROR and adds the active exception.1

Go

log/slog was designed for key-value records. JSONHandler writes one JSON object per record and TextHandler writes key=value pairs. HandlerOptions.Level sets the minimum level, and the default is Info. HandlerOptions.ReplaceAttr can rename, change or remove any attribute. The examples remove the time, so the output is the same on each run.3 A call with a missing key does not fail: slog writes the value under the key !BADKEY.3 go vet has a slog check that reports these calls.4

Java

Java has two APIs in the JDK. java.util.logging has the levels SEVERE, WARNING, INFO, CONFIG, FINE, FINER and FINEST.7 System.Logger, from JEP 264, is a small API that the JDK's own classes use. A service can plug in any logging backend.10 By default, System.Logger sends records to java.util.logging when the java.logging module is present. Its levels map to that backend: TRACE to FINER, DEBUG to FINE, ERROR to SEVERE.5 6

The default ConsoleHandler writes to System.err with SimpleFormatter.8 The output of SimpleFormatter starts with the date and time. The example replaces it with a handler that writes to System.out with a fixed format. Neither API has key-value pairs. A program puts the fields in the message, and MessageFormat formats a number argument by the locale, so {0} turns 1042 into 1,042.9

C# and .NET

The .NET logging API, ILogger, supports structured logging with message templates. In "Order {OrderId} placed", OrderId becomes the name of a field. The order of the placeholders, not their names, decides which argument fills each one. The documentation warns that string interpolation in a log call can cause performance issues.11 ILogger is in the package Microsoft.Extensions.Logging, so the example writes JSON with Utf8JsonWriter from the base library instead.

Rust

The standard library has no logger. The log crate is a facade: libraries call its macros error!, warn!, info!, debug! and trace!, and the application selects one implementation. If none is selected, the facade falls back to a logger that does nothing. The crate's kv feature adds structured key-value pairs.12 The example uses no crate and writes key=value pairs with {:?}, which quotes and escapes each string.

JavaScript, TypeScript, C and C++

These languages have no logger with levels in the standard library. A logger is a few lines: a level check and a function that writes one escaped record. In JavaScript, JSON.stringify does the escaping. In C, the program must escape quotes and newlines itself. C++ std::print with {:?} writes an escaped string.

PythonGitHub
import json
import logging
import sys


class JsonFormatter(logging.Formatter):
    """Writes each record as one JSON object, with no timestamp."""

    def format(self, record):
        entry = {"level": record.levelname, "logger": record.name, "msg": record.getMessage()}
        entry.update(getattr(record, "fields", {}))
        if record.exc_info:
            entry["error"] = repr(record.exc_info[1])
        return json.dumps(entry)


handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
log = logging.getLogger("shop")
log.addHandler(handler)
log.setLevel(logging.INFO)

log.debug("cart loaded", extra={"fields": {"items": 3}})  # below INFO: dropped
log.info("order placed", extra={"fields": {"order": 1042, "total_cents": 1999}})
log.warning("stock low", extra={"fields": {"sku": "A-17", "left": 2}})
user = 'bob\n{"level": "INFO", "msg": "login ok"}'  # text from a request
log.info("login failed", extra={"fields": {"user": user}})
try:
    1 / 0
except ZeroDivisionError:
    log.exception("price failed", extra={"fields": {"order": 1043}})
print(logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
Output
{"level": "INFO", "logger": "shop", "msg": "order placed", "order": 1042, "total_cents": 1999}
{"level": "WARNING", "logger": "shop", "msg": "stock low", "sku": "A-17", "left": 2}
{"level": "INFO", "logger": "shop", "msg": "login failed", "user": "bob\n{\"level\": \"INFO\", \"msg\": \"login ok\"}"}
{"level": "ERROR", "logger": "shop", "msg": "price failed", "order": 1043, "error": "ZeroDivisionError('division by zero')"}
10 20 30 40 50

The default level of the root logger is WARNING. A program that logs at INFO and does not set a level sees nothing.

This code runs but gives a wrong answer on purpose.

import logging
import sys

logging.basicConfig(stream=sys.stdout, format="%(levelname)s %(message)s")
logging.info("server started")  # below the default level WARNING
logging.warning("disk %d%% full", 91)
Output
WARNING disk 91% full

A plain text format writes the user's text as it is. A newline in the text starts a second line that looks like a real record. The JSON formatter above writes the same text as \n inside one string.

This code runs but gives a wrong answer on purpose.

import logging
import sys

logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(levelname)s %(message)s")
user = "bob\nINFO login ok user=admin"  # text from a request
logging.info("login failed user=%s", user)
Output
INFO login failed user=bob
INFO login ok user=admin

The logging module formats the message only when a handler will write the record. The arguments are still computed before the call. An f-string builds the whole message even when the record is dropped.

import logging
import sys

calls = 0


class Cart:
    def __str__(self):
        global calls
        calls += 1
        return "Cart(3 items)"


logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(levelname)s %(message)s")
log = logging.getLogger("shop")
cart = Cart()

log.debug("cart %s", cart)  # dropped before the message is formatted
print("after %-style call:", calls)
log.debug(f"cart {cart}")  # the f-string is built first, then dropped
print("after f-string call:", calls)
if log.isEnabledFor(logging.DEBUG):  # skips the work when DEBUG is off
    log.debug("cart %s", cart)
log.info("cart %s", cart)
print("after info call:", calls)
Output
after %-style call: 0
after f-string call: 1
INFO cart Cart(3 items)
after info call: 2
  • Verdict: stdlib. The logging module has levels, named loggers in a hierarchy, handlers and formatters.
  • The module has no JSON formatter. A subclass of logging.Formatter writes each record as JSON, and extra= adds fields to the record.
  • log.exception logs at ERROR and adds the active exception to the record.
  • Pass the arguments after a %s format string instead of an f-string, so that a dropped record is not formatted.
#include <print>
#include <source_location>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

enum class Level { debug, info, warn, error };

constexpr std::string_view name(Level level) {
    constexpr std::string_view names[] = {"debug", "info", "warn", "error"};
    return names[static_cast<int>(level)];
}

struct Logger {
    Level min;

    // Writes one line of key=value pairs, with no timestamp. {:?} quotes and escapes strings.
    void log(Level level, std::string_view msg, const std::vector<std::pair<std::string_view, std::string>> &fields = {},
             std::source_location where = std::source_location::current()) const {
        if (level < min) {
            return;
        }
        std::print("level={} msg={:?} line={}", name(level), msg, where.line());
        for (const auto &[key, value] : fields) {
            std::print(" {}={:?}", key, value);
        }
        std::println("");
    }
};

int main() {
    Logger log{Level::info};
    log.log(Level::debug, "cart loaded", {{"items", "3"}}); // below info: dropped
    log.log(Level::info, "order placed", {{"order", std::to_string(1042)}});
    log.log(Level::warn, "stock low", {{"sku", "A-17"}, {"left", std::to_string(2)}});
    std::string user = "bob\nlevel=info msg=\"login ok\"";
    log.log(Level::info, "login failed", {{"user", user}});
}
Output
level=info msg="order placed" line=35 order="1042"
level=warn msg="stock low" line=36 sku="A-17" left="2"
level=info msg="login failed" line=38 user="bob\nlevel=info msg=\"login ok\""
  • Verdict: idiom. The C++ standard library has no logger.
  • The {:?} format of std::print writes a string in quotes, with escapes for a newline and a quote.
  • A default argument of type std::source_location takes the line of the caller, so each record shows where it came from.
JavaGitHub
import java.util.Locale;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.StreamHandler;

public class Main {
    // Writes the level, the logger and the message, with no timestamp.
    static class KeyValueFormatter extends Formatter {
        @Override
        public String format(LogRecord r) {
            return "level=" + r.getLevel().getName() + " logger=" + r.getLoggerName()
                + " msg=\"" + formatMessage(r) + "\"" + System.lineSeparator();
        }
    }

    public static void main(String[] args) {
        Locale.setDefault(Locale.US); // MessageFormat formats numbers by locale
        // Replace the default ConsoleHandler, which writes to System.err with a timestamp.
        Logger root = Logger.getLogger("");
        for (Handler h : root.getHandlers()) {
            root.removeHandler(h);
        }
        Handler out = new StreamHandler(System.out, new KeyValueFormatter());
        out.setLevel(Level.ALL);
        root.addHandler(out);
        root.setLevel(Level.FINE);

        // java.util.logging directly
        Logger jul = Logger.getLogger("shop");
        jul.finer("cart loaded"); // below FINE: dropped
        jul.log(Level.INFO, "order placed order={0} total_cents={1}", new Object[] {1042, 1999});
        jul.log(Level.INFO, "order placed order={0,number,#} total_cents={1,number,#}", new Object[] {1042, 1999});

        // System.Logger, the platform API; here it forwards to java.util.logging
        System.Logger sys = System.getLogger("shop.stock");
        sys.log(System.Logger.Level.TRACE, "scan started"); // maps to FINER: dropped
        sys.log(System.Logger.Level.DEBUG, "cache hit sku={0}", "A-17"); // maps to FINE
        sys.log(System.Logger.Level.WARNING, "stock low sku={0} left={1}", "A-17", 2);
        out.flush();
    }
}
Output
level=INFO logger=shop msg="order placed order=1,042 total_cents=1,999"
level=INFO logger=shop msg="order placed order=1042 total_cents=1999"
level=FINE logger=shop.stock msg="cache hit sku=A-17"
level=WARNING logger=shop.stock msg="stock low sku=A-17 left=2"
  • Verdict: stdlib. java.util.logging has levels, named loggers, handlers and formatters. System.Logger is the platform logging API, and by default it sends records to java.util.logging.
  • The default ConsoleHandler writes to System.err with a timestamp, so the program replaces it with a handler that writes to System.out with a fixed format.
  • System.Logger levels map to java.util.logging levels: TRACE to FINER and DEBUG to FINE.
  • Neither API has key-value pairs. The fields go in the message, and MessageFormat formats a number by locale, so {0} gives 1,042. Use {0,number,#} for a value that a machine reads.
#include <stdio.h>
#include <string.h>

enum level { LEVEL_DEBUG, LEVEL_INFO, LEVEL_WARN, LEVEL_ERROR };
static const char *level_names[] = {"debug", "info", "warn", "error"};
static enum level min_level = LEVEL_INFO;

// Writes s in double quotes, with backslash escapes for quotes,
// backslashes and control characters, so that s stays on one line.
static void put_quoted(FILE *out, const char *s) {
    fputc('"', out);
    for (; *s != '\0'; s++) {
        unsigned char c = (unsigned char)*s;
        if (c == '"' || c == '\\') {
            fprintf(out, "\\%c", c);
        } else if (c == '\n') {
            fputs("\\n", out);
        } else if (c < 0x20) {
            fprintf(out, "\\x%02x", c);
        } else {
            fputc(c, out);
        }
    }
    fputc('"', out);
}

// Writes one record: the level, the message and one string field.
static void log_kv(enum level level, const char *msg, const char *key, const char *value) {
    if (level < min_level) {
        return;
    }
    printf("level=%s msg=", level_names[level]);
    put_quoted(stdout, msg);
    printf(" %s=", key);
    put_quoted(stdout, value);
    putchar('\n');
}

int main(void) {
    log_kv(LEVEL_DEBUG, "cart loaded", "items", "3"); // below info: dropped
    log_kv(LEVEL_INFO, "order placed", "order", "1042");
    log_kv(LEVEL_WARN, "stock low", "sku", "A-17");
    const char *user = "bob\nlevel=info msg=\"login ok\" user=admin"; // from a request
    log_kv(LEVEL_INFO, "login failed", "user", user);
}
Output
level=info msg="order placed" order="1042"
level=warn msg="stock low" sku="A-17"
level=info msg="login failed" user="bob\nlevel=info msg=\"login ok\" user=admin"

Without escaping, the user's newline starts a forged record.

This code runs but gives a wrong answer on purpose.

#include <stdio.h>

int main(void) {
    const char *user = "bob\nlevel=info msg=\"login ok\" user=admin"; // from a request
    printf("level=info msg=\"login failed\" user=%s\n", user);
}
Output
level=info msg="login failed" user=bob
level=info msg="login ok" user=admin
  • Verdict: idiom. ISO C has no logger. A program writes records with fprintf. POSIX systems also have syslog.
  • put_quoted escapes quotes, backslashes and control characters, so each value stays inside its quotes and on one line.
  • A field of another type must be converted to a string first, so the example passes the numbers as strings.
using System.Text.Json;

var log = new JsonLog(Level.Information);
log.Write(Level.Debug, "cart loaded", ("items", 3)); // below Information: dropped
log.Write(Level.Information, "order placed", ("order", 1042), ("total_cents", 1999));
log.Write(Level.Warning, "stock low", ("sku", "A-17"), ("left", 2));
log.Write(Level.Information, "login failed", ("user", "bob\n{\"level\":\"Information\"}"));
try
{
    checked { int cents = int.MaxValue; cents += 1; }
}
catch (OverflowException e)
{
    log.Write(Level.Error, "total failed", ("error", e.GetType().Name), ("order", 1043));
}

// The levels of Microsoft.Extensions.Logging.LogLevel, with the same numbers.
enum Level { Trace, Debug, Information, Warning, Error, Critical }

// Writes one JSON object per line, with no timestamp.
class JsonLog(Level minLevel)
{
    public void Write(Level level, string message, params (string Key, object Value)[] fields)
    {
        if (level < minLevel)
        {
            return;
        }
        using var stream = Console.OpenStandardOutput();
        using (var json = new Utf8JsonWriter(stream))
        {
            json.WriteStartObject();
            json.WriteString("level", level.ToString());
            json.WriteString("msg", message);
            foreach (var (key, value) in fields)
            {
                switch (value)
                {
                    case int number: json.WriteNumber(key, number); break;
                    case bool flag: json.WriteBoolean(key, flag); break;
                    default: json.WriteString(key, value.ToString()); break;
                }
            }
            json.WriteEndObject();
        }
        stream.WriteByte((byte)'\n');
    }
}
Output
{"level":"Information","msg":"order placed","order":1042,"total_cents":1999}
{"level":"Warning","msg":"stock low","sku":"A-17","left":2}
{"level":"Information","msg":"login failed","user":"bob\n{\u0022level\u0022:\u0022Information\u0022}"}
{"level":"Error","msg":"total failed","error":"OverflowException","order":1043}
  • Verdict: library. ILogger in Microsoft.Extensions.Logging is the logging API of .NET applications, and it comes as a package. The base library has System.Text.Json, which writes the JSON here.
  • The levels of the example have the numbers of LogLevel: Trace is 0 and Critical is 5.
  • Utf8JsonWriter escapes the newline and, by default, writes the quote as \u0022.
JavaScriptGitHub
const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };

// Returns a logger that writes one JSON object per line, with no timestamp.
function createLogger(minLevel, fields = {}) {
  const log = (level, msg, extra = {}) => {
    if (LEVELS[level] < LEVELS[minLevel]) {
      return;
    }
    console.log(JSON.stringify({ level, msg, ...fields, ...extra }));
  };
  return {
    debug: (msg, extra) => log("debug", msg, extra),
    info: (msg, extra) => log("info", msg, extra),
    warn: (msg, extra) => log("warn", msg, extra),
    error: (msg, extra) => log("error", msg, extra),
    child: (more) => createLogger(minLevel, { ...fields, ...more }),
  };
}

const log = createLogger("info");
log.debug("cart loaded", { items: 3 }); // below info: dropped
log.info("order placed", { order: 1042, totalCents: 1999 });
const req = log.child({ request: "r-7" });
req.warn("stock low", { sku: "A-17", left: 2 });
req.info("login failed", { user: "bob\n{\"level\":\"info\",\"msg\":\"login ok\"}" });
function price(cents) {
  if (cents <= 0) {
    throw new RangeError("price must be positive");
  }
  return cents;
}

try {
  price(-5);
} catch (err) {
  req.error("bad cart", { error: err.name, detail: err.message });
}
Output
{"level":"info","msg":"order placed","order":1042,"totalCents":1999}
{"level":"warn","msg":"stock low","request":"r-7","sku":"A-17","left":2}
{"level":"info","msg":"login failed","request":"r-7","user":"bob\n{\"level\":\"info\",\"msg\":\"login ok\"}"}
{"level":"error","msg":"bad cart","request":"r-7","error":"RangeError","detail":"price must be positive"}

JSON.stringify writes only the own enumerable properties of an object. The name, message and stack of an Error are not enumerable, so an error becomes {}.

This code runs but gives a wrong answer on purpose.

function price(cents) {
  if (cents <= 0) {
    throw new RangeError("price must be positive");
  }
  return cents;
}

try {
  price(-5);
} catch (err) {
  console.log(JSON.stringify({ level: "error", msg: "bad cart", error: err }));
}
Output
{"level":"error","msg":"bad cart","error":{}}
  • Verdict: idiom. console.log, console.warn and console.error write text. A logger with levels and fields is a few lines over JSON.stringify.
  • JSON.stringify escapes the newline in the user's text, so the text stays in one record.
  • Copy the name and message of an error into fields. An Error object serializes as {}.
TypeScriptGitHub
type Level = "debug" | "info" | "warn" | "error";
type Fields = Record<string, string | number | boolean>;

const rank: Record<Level, number> = { debug: 10, info: 20, warn: 30, error: 40 };

class Logger {
  private readonly minLevel: Level;
  private readonly fields: Fields;

  constructor(minLevel: Level, fields: Fields = {}) {
    this.minLevel = minLevel;
    this.fields = fields;
  }

  log(level: Level, msg: string, extra: Fields = {}): void {
    if (rank[level] < rank[this.minLevel]) {
      return;
    }
    console.log(JSON.stringify({ level, msg, ...this.fields, ...extra }));
  }

  child(more: Fields): Logger {
    return new Logger(this.minLevel, { ...this.fields, ...more });
  }
}

const log = new Logger("info");
log.log("debug", "cart loaded", { items: 3 }); // below info: dropped
log.log("info", "order placed", { order: 1042, totalCents: 1999 });
const req = log.child({ request: "r-7" });
req.log("warn", "stock low", { sku: "A-17", left: 2 });
req.log("error", "payment refused", { order: 1043, retry: false });
Output
{"level":"info","msg":"order placed","order":1042,"totalCents":1999}
{"level":"warn","msg":"stock low","request":"r-7","sku":"A-17","left":2}
{"level":"error","msg":"payment refused","request":"r-7","order":1043,"retry":false}
  • Verdict: idiom. The program is the JavaScript logger with types.
  • The union type Level lets the compiler reject a level name that does not exist.
  • Fields allows only strings, numbers and booleans as values, so an Error object cannot go into a record by mistake.
package main

import (
	"errors"
	"log/slog"
	"os"
)

// Password is a secret. Its LogValue hides it in every log record.
type Password string

func (Password) LogValue() slog.Value { return slog.StringValue("REDACTED") }

func main() {
	opts := &slog.HandlerOptions{
		Level: slog.LevelInfo,
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey && len(groups) == 0 {
				return slog.Attr{} // drop the time so that the output is fixed
			}
			return a
		},
	}
	log := slog.New(slog.NewJSONHandler(os.Stdout, opts))

	log.Debug("cart loaded", "items", 3) // below Info: dropped
	log.Info("order placed", "order", 1042, "total_cents", 1999)
	req := log.With("request", "r-7")
	req.Warn("stock low", slog.String("sku", "A-17"), slog.Int("left", 2))
	req.Error("price failed", "order", 1043, "err", errors.New("division by zero"))
	req.Info("login", "user", "bob", "password", Password("hunter2"))

	text := slog.New(slog.NewTextHandler(os.Stdout, opts))
	text.Info("order placed", "order", 1042, "note", "gift wrap")
}
Output
{"level":"INFO","msg":"order placed","order":1042,"total_cents":1999}
{"level":"WARN","msg":"stock low","request":"r-7","sku":"A-17","left":2}
{"level":"ERROR","msg":"price failed","request":"r-7","order":1043,"err":"division by zero"}
{"level":"INFO","msg":"login","request":"r-7","user":"bob","password":"REDACTED"}
level=INFO msg="order placed" order=1042 note="gift wrap"

A log call takes pairs of a key and a value. A missing key shifts the pairs, and slog writes the value under the key !BADKEY. go vet reports these calls.

This code runs but gives a wrong answer on purpose.

package main

import (
	"log/slog"
	"os"
)

func main() {
	opts := &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey && len(groups) == 0 {
				return slog.Attr{}
			}
			return a
		},
	}
	log := slog.New(slog.NewJSONHandler(os.Stdout, opts))
	order, total := 1042, 1999
	log.Info("order placed", "order", order, total) // the key "total_cents" is missing
	log.Info("order placed", order, total)          // no keys at all
}
Output
{"level":"INFO","msg":"order placed","order":1042,"!BADKEY":1999}
{"level":"INFO","msg":"order placed","!BADKEY":1042,"!BADKEY":1999}
  • Verdict: stdlib. log/slog writes records with a time, a level, a message and key-value attributes.
  • JSONHandler writes JSON and TextHandler writes key=value pairs. ReplaceAttr can change or remove any attribute, here the time.
  • Logger.With adds attributes to every record of a new logger, such as the id of a request.
  • A type with a LogValue method controls how it appears in a record, so a password type can always print REDACTED.
RustGitHub
use std::fmt::Write;

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
enum Level {
    Trace,
    Debug,
    Info,
    Warn,
    Error,
}

struct Logger {
    min: Level,
}

impl Logger {
    // Writes one line of key=value pairs, with no timestamp.
    // {:?} quotes each string and escapes newlines and quotes in it.
    fn log(&self, level: Level, msg: &str, fields: &[(&str, &dyn std::fmt::Debug)]) {
        if level < self.min {
            return;
        }
        let mut line = format!("level={level:?} msg={msg:?}");
        for (key, value) in fields {
            write!(line, " {key}={value:?}").unwrap();
        }
        println!("{line}");
    }
}

fn main() {
    let log = Logger { min: Level::Info };
    log.log(Level::Trace, "scan started", &[]); // below Info: dropped
    log.log(Level::Debug, "cart loaded", &[("items", &3)]); // dropped
    log.log(Level::Info, "order placed", &[("order", &1042), ("total_cents", &1999)]);
    log.log(Level::Warn, "stock low", &[("sku", &"A-17"), ("left", &2)]);
    let user = "bob\nlevel=Info msg=\"login ok\"";
    log.log(Level::Info, "login failed", &[("user", &user)]);
    match "12x".parse::<u32>() {
        Ok(qty) => log.log(Level::Info, "quantity", &[("qty", &qty)]),
        Err(e) => log.log(Level::Error, "bad quantity", &[("input", &"12x"), ("error", &e.to_string())]),
    }
}
Output
level=Info msg="order placed" order=1042 total_cents=1999
level=Warn msg="stock low" sku="A-17" left=2
level=Info msg="login failed" user="bob\nlevel=Info msg=\"login ok\""
level=Error msg="bad quantity" input="12x" error="invalid digit found in string"
  • Verdict: library. The log crate is the common logging facade. Without a logger implementation, its macros do nothing. The standard library has no logger.
  • The {:?} format quotes a string and escapes a newline and a quote in it, so a field stays on one line.
  • #[derive(PartialOrd)] orders the variants of Level by their position, so level < self.min filters the records.

The system log

On Unix systems, syslog collects the logs of many programs in one place. It started on BSD, and Eric Allman wrote the daemon and the protocol.16 Each message has a facility, which names the part of the system, and a severity from 0 to 7.17 On POSIX systems with the XSI option, a C program calls syslog(), and a shell script calls the logger utility. Both send a message to a logging facility that the implementation defines.18 19

Debug output and logging

A print added for one debug session is not a log. It has no level, and it is removed after the bug is fixed. A log record stays in the code, and the level decides when it appears. Interactive debugging stops a program to look at its state. A log is often the only view of a program that runs in production.

Pitfalls

Secrets and personal data in the log

A log goes to more places than the data it describes: files, backups, a search service, the screens of support staff. CWE-532 describes the weakness: "The product writes sensitive information to a log file."15 The OWASP Logging Cheat Sheet lists data that should not be recorded directly, but be removed, masked, hashed or encrypted: session ids, access tokens, passwords, database connection strings, encryption keys, payment card data and sensitive personal data.13 See Exposure of sensitive information and Hard-coded credentials.

The safe place for redaction is the type of the value, not each call. In Go, a Password type with a LogValue method prints REDACTED in every record.3 A whole request or a whole user object in a log record often holds a secret that nobody meant to log.

Log injection

A log that writes user text as it is lets the user write records. A newline in a user name ends the record, and the rest of the name becomes a forged record. CWE-117 names this weakness, also called log forging: the program "constructs a log message from external input, but it does not neutralize" the special elements in it.14 OWASP says: "Do not use unstructured text log formats", and recommends structured formats such as JSON.13 The Python and C examples show a forged record. The JSON and {:?} examples keep the same text inside one field.

The record is dropped and nobody sees it

A level set too high hides the records that would explain a failure. In Python, the default level is WARNING, so logging.info prints nothing until the program sets a level.2 In Java, a ConsoleHandler has the level INFO by default, so it does not write FINE records.8

Work done for a dropped record

The arguments of a log call are computed before the level check. An f-string in Python or string interpolation in C# builds the whole message even when the record is dropped.2 11 Pass the values as arguments, check the level first, or use a type that computes its value only when the record is written, such as Go's LogValuer.2 3

Fields that a machine cannot read

A field must have one type and one format. 1,042 in one record and 1042 in the next break a query. In Java, MessageFormat formats numbers by the locale.9 An error object can also turn into nothing: JSON.stringify writes only enumerable properties, and the message of an Error is not one, so the record gets {}. Copy the name and the message of an error into fields.

Timestamps in tests

A record usually has the time of the event. A test that compares log output must remove the time or set a fixed clock. The examples on this page remove it: Go with ReplaceAttr, the other languages with a formatter that does not write it.

Cost

A log record costs a level check, the formatting of the record and a write. The level check is a comparison of two numbers. The formatting allocates strings. The write is a system call or a copy into a buffer. Go's documentation lists ways to reduce the cost: Logger.With formats common fields once, and a LogValuer defers expensive work until the record is enabled.3 Python's documentation recommends isEnabledFor before expensive arguments.2

The larger cost is often storage. A server that writes a record for each request writes millions of records a day. Debug records are usually off in production for this reason.

History

  • BSD syslog. Eric Allman wrote the syslog daemon and protocol. The protocol started on the BSD TCP/IP system and was then ported to many other systems and devices.16
  • 2001. RFC 3164 described the BSD syslog protocol as it was observed in use. It had a priority and free text, with no fields.16
  • 2009. RFC 5424, by Rainer Gerhards, replaced RFC 3164. It defined the severities 0 to 7 and STRUCTURED-DATA, named parameters inside a syslog message.17
  • 2014. Daniel Fuchs created JEP 264, the Platform Logging API and Service, which became System.Logger in Java.10

References

  1. Python documentation, logging, Logging facility for Python, Logger Objects (debug and its keyword argument extra, exception); Logging Levels; LoggerAdapter Objects
  2. Python documentation, Logging HOWTO, Basic Logging Tutorial (the default level is WARNING); Optimization
  3. Go standard library, package log/slog, the overview; Levels; Customizing a type's logging behavior; Performance considerations; HandlerOptions; Logger.Log
  4. Go command vet, the list of checks (slog, check for invalid structured logging calls)
  5. Java SE 25 API, System.Logger.Level, the class description (System.Logger Severity Level Mapping)
  6. Java SE 25 API, System.LoggerFinder, Default Implementation
  7. Java SE 25 API, java.util.logging.Level, the class description (the levels in descending order)
  8. Java SE 25 API, java.util.logging.ConsoleHandler, the class description (publishes to System.err with SimpleFormatter)
  9. Java SE 25 API, java.text.MessageFormat, the table of FormatType and FormatStyle; the table of format(Object[], StringBuffer, FieldPosition) (an argument instanceof Number)
  10. JEP 264, Platform Logging API and Service, the header (owner, created) and Summary
  11. .NET documentation, Logging in C# and .NET, the introduction; Log level; Log message template
  12. Rust crate log, documentation, the crate description; Use; Structured logging
  13. OWASP Cheat Sheet Series, Logging Cheat Sheet, Event attributes; Data to exclude; Log Injection
  14. CWE-117, Improper Output Neutralization for Logs, Description; Alternate Terms
  15. CWE-532, Insertion of Sensitive Information into Log File, Description
  16. C. Lonvick, RFC 3164, The BSD syslog Protocol, August 2001, Abstract; 4.1 syslog Message Parts; Acknowledgements
  17. R. Gerhards, RFC 5424, The Syslog Protocol, March 2009, 6.2.1 PRI (Table 2, Syslog Message Severities); 6.3 STRUCTURED-DATA; 6.3.3 SD-PARAM; 6.3.5 Examples
  18. POSIX.1-2024, closelog, openlog, setlogmask, syslog, SYNOPSIS (XSI); DESCRIPTION
  19. POSIX.1-2024, logger, DESCRIPTION

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/7J7FQX/text.yaml