nanolog

agent
Guvenlik Denetimi
Uyari
Health Uyari
  • License — License: Apache-2.0
  • Description — Repository has a description
  • Active repo — Last push 0 days ago
  • Low visibility — Only 6 GitHub stars
Code Gecti
  • Code scan — Scanned 12 files during light audit, no dangerous patterns found
Permissions Gecti
  • Permissions — No dangerous permissions requested

Bu listing icin henuz AI raporu yok.

SUMMARY

Zero-dependency Java 8+ logging library built for AI coding agents: agent mode cuts the log tokens an agent reads (13,577 to 1,058 on a failing test run), LOG.dbg print debugging that shows each expression with its value, wide events with one canonical log line per request, static LOG calls without logger fields, JSON lines and an SLF4J bridge.

README.md

[ en | ru ]

CI build status
Maven Central
API documentation on javadoc.io
Java 8 or newer
License: Apache-2.0
OpenSSF Best Practices
GitHub stars

 Nanolog: Java logging with fewer tokens for AI coding agents

Nanolog is a zero-dependency logging library for Java 8+ that keeps console output short when an AI
coding agent runs your code. Under Claude Code, Codex, Gemini CLI or Cursor CLI the console keeps
warnings, errors and LOG.dbg, one line each, and the run ends with a summary; the full log goes
to a file. A failing test run printed 1,058 tokens instead of 13,577 (o200k_base, see
Fewer tokens). Without an agent the console prints every level.

Every call goes through the static methods of LOG, and the source class is detected automatically,
so no class needs a logger field. The library prints to the console, writes JSON lines, captures entries
in tests, and works on its own or on top of SLF4J, and therefore on top of Logback, Log4j 2,
JBoss Logging and others.

Questions and feedback: Discussions · bugs: Issues · English or Russian

Nanolog for Java (com.nanolaba:nanolog) is not related to NanoLog, the nanosecond-scale logger for C++.

Try it

<dependency>
    <groupId>com.nanolaba</groupId>
    <artifactId>nanolog</artifactId>
    <version>1.4.1</version>
</dependency>
implementation("com.nanolaba:nanolog:1.4.1")
import com.nanolaba.logging.LOG;

import java.math.BigDecimal;

public class TryIt {

    public static void main(String[] args) {
        BigDecimal price = new BigDecimal("43.30");
        int quantity = 3;
        LOG.info("Checkout of {} items", quantity);
        LOG.dbg(price.multiply(BigDecimal.valueOf(quantity)));
    }
}
INFO 17.11.2026 10:15:02 [TryIt] Checkout of 3 items
DBG 17.11.2026 10:15:02 [TryIt.main(TryIt.java:11)] price.multiply(BigDecimal.valueOf(quantity)) = 129.90 (BigDecimal)
[NANOLOG] 1 LOG.dbg call ran in this JVM: TryIt.java:11

LOG.dbg prints the expression as written, its value and type, and the call site, and returns the value; the last line reminds you to remove the call. More in Print debugging and Quick start.

When a coding agent runs the same program (here with AI_AGENT=claude-code), the INFO line goes only to the run log, and the run ends with a summary:

[NANOLOG] Agent mode (AI_AGENT=claude-code): the console shows WARN, ERROR and every LOG.dbg; the full log is in /home/me/shop/target/nanolog/latest.log, WARN and ERROR also in /home/me/shop/target/nanolog/latest.errors.log; nanolog.agent=off turns it off
DBG [TryIt.main(TryIt.java:11)] price.multiply(BigDecimal.valueOf(quantity)) = 129.90 (BigDecimal)
[NANOLOG] Run summary: 2 entries: 1 INFO, 1 DEBUG; the full log is in /home/me/shop/target/nanolog/latest.log
[NANOLOG]   1 LOG.dbg call ran in this JVM: TryIt.java:11

More in Agent mode and Fewer tokens.

Why Nanolog

  • Fewer tokens for AI coding agents. Since 1.4. When Claude Code, Gemini CLI, Codex, Cursor CLI or another agent that sets AI_AGENT runs the program, the console keeps WARN, ERROR and LOG.dbg, and the full log goes to target/nanolog/latest.log. A failing test run printed 1,058 tokens instead of 13,577, the run summary included, and a green one 178 instead of 16,550 (o200k_base); see Fewer tokens.
  • A summary that survives truncation. Since 1.4. Agents often keep only the head and the tail of a long output; in agent mode the run ends with the counts by level, each kind of warning and error with its call site, and the trace of the first error; see Run summary.
  • Print debugging that names its values. Since 1.4. LOG.dbg(order.total()) prints order.total() = 129.90 (BigDecimal) with the file and line of the call and returns the value, like dbg! in Rust and icecream in Python; objects without toString() are shown field by field instead of Order@2f92e0f4; see Print debugging.
  • Wide events, one line per request. Since 1.4. LOG.unit("checkout") writes one canonical log line per request or job when it ends: outcome, duration, your fields and the count of warnings and errors logged inside it, checkout ok 182 ms orderId=A-17 warn=1; failed units carry a stable error key; see Wide events.
  • No logger fields. LOG.info("...") works from any class; the caller is found by walking the stack.
  • Zero dependencies. No transitive libraries; slf4j-api is needed only if you use Slf4jLogger.
  • SLF4J-style placeholders. {} with escaping, array rendering and sane handling of missing or extra arguments.
  • JSON lines and tests built in. JsonLogger writes one JSON object per line for jq and log collectors; MemoryLogger captures entries in a test and asserts on them, with the whole log in the failure message; see JsonLogger and MemoryLogger and CompositeLogger.
  • Levels change at run time. LOG.setLevel("com.acme.payments", DEBUG) from an admin endpoint or a test takes effect in every thread, and LOG.withLevel(...) puts the old level back when the block ends; see Changing levels at run time.
  • Logging never throws. A broken toString() becomes [FAILED toString()] instead of an exception in your code.
  • Lazy messages. LOG.debug(() -> ...) is evaluated only when the level is enabled.
  • Pluggable. A custom backend is one lambda or one class implementing ILogger.
  • Fits the agent loop. One line per log call apart from stack traces, output from the first run, an API that fits in one context window; see Agent-driven development.

How Nanolog compares with tinylog, SLF4J, Log4j 2, Flogger and others: Related projects.

The latest stable version is 1.4.1; the version under development is 1.5-SNAPSHOT (see Changelog).

Table of contents

Installation

Maven (pom.xml)

<dependency>
    <groupId>com.nanolaba</groupId>
    <artifactId>nanolog</artifactId>
    <version>1.4.1</version>
</dependency>

Gradle (build.gradle)

dependencies {
    implementation 'com.nanolaba:nanolog:1.4.1'
}

Manual download

Get the JAR from Maven Central and add it to the classpath.

Requirements: Java 8+. On Java 9+ the jar is the module com.nanolaba.nanolog, which needs only java.base (SLF4J and JUnit are optional), so it works on the module path and in a runtime image built with jlink. A logger class named in nanolog.logger must be in a package its module exports. On the module path JUnit does not find NanologExtension by itself: register it with @ExtendWith(NanologExtension.class).

The same jar serves Kotlin: CI compiles every kind of LOG call from Kotlin, LOG.info { "lazy" } among them, so no overload is ambiguous there. A block given to LOG.timed or LOG.unit takes the overload that returns nothing; for the value of the block write val n = LOG.timed("Count users", Supplier { repo.count() }).

Native image and Android

Since 1.4.

  • GraalVM native image. The jar carries its metadata in META-INF/native-image: the constructors of the loggers that nanolog.logger names, the stack walker of caller detection and the resource nanolog.properties. CI builds a native image on GraalVM 21 and 25 that logs through ConsoleLogger and through JsonLogger chosen with -Dnanolog.logger. A class of your own named in nanolog.logger or nanolog.context.provider needs its constructor registered by you, and a class that LOG.dbg or nanolog.dump prints field by field needs its fields registered. LOG.dbg prints values without the expression text, since there are no source files at run time.
  • Android and R8. The jar carries META-INF/proguard/nanolog.pro, which R8 and ProGuard apply by themselves: it keeps the constructors of the loggers and the attributes that caller detection reads, and silences the warnings about SLF4J and JUnit, which an app may not have. Obfuscation renames your classes in the log as it does in stack traces; the mapping file restores them (retrace). Nanolog is not tested on Android.

Quick start

No setup is needed: ConsoleLogger is active by default and prints every level, including TRACE; when a coding agent runs the program, the console is shorter, see Agent mode.

import com.nanolaba.logging.LOG;

public class QuickStart {

    public static void main(String[] args) {
        // No logger field: the source class is detected automatically
        LOG.info("Application started");

        // SLF4J-style {} placeholders
        LOG.debug("Loaded {} items in {} ms", 42, 17);

        // Lazy message: the lambda runs only if DEBUG is enabled
        LOG.debug(() -> "Expensive report: " + buildReport());

        // The context adds requestId=r-17 to every entry in the block;
        // the unit writes one line when it ends: outcome, duration, fields, warnings
        try (LOG.Context context = LOG.context("requestId", "r-17");
             LOG.Unit checkout = LOG.unit("checkout")) {
            checkout.put("orderId", "A-17");
            LOG.warn("Card declined, retrying");
            LOG.info("Payment accepted", LOG.kv("method", "card")); // a named field
        }

        // A timer that returns the value of the lambda
        String report = LOG.timed("Build report", () -> buildReport());

        // Print debugging: the expression as written, its value, type and call site
        LOG.dbg(report.length());

        String input = "not a number";
        try {
            Integer.parseInt(input);
        } catch (NumberFormatException e) {
            // Exception plus a parameterized message; the stack trace follows the message
            LOG.error(e, "Failed to parse \"{}\"", input);
        }
    }

    private static String buildReport() {
        return "...";
    }
}

Console output (ERROR goes to System.err, everything else to System.out):

INFO 10.11.2026 21:30:00 [QuickStart] Application started
DEBUG 10.11.2026 21:30:00 [QuickStart] Loaded 42 items in 17 ms
DEBUG 10.11.2026 21:30:00 [QuickStart] Expensive report: ...
WARN 10.11.2026 21:30:00 [QuickStart] Card declined, retrying requestId=r-17
INFO 10.11.2026 21:30:00 [QuickStart] Payment accepted method=card requestId=r-17
INFO 10.11.2026 21:30:00 [QuickStart] checkout ok 6 ms orderId=A-17 warn=1 requestId=r-17
INFO 10.11.2026 21:30:00 [QuickStart] Build report took 0 ms
DBG 10.11.2026 21:30:00 [QuickStart.main(QuickStart.java:28)] report.length() = 3 (Integer)
ERROR 10.11.2026 21:30:00 [QuickStart] Failed to parse "not a number" java.lang.NumberFormatException: For input string: "not a number"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	...
[NANOLOG] 1 LOG.dbg call ran in this JVM: QuickStart.java:28

With -Dnanolog.logger=com.nanolaba.logging.JsonLogger the same entries are JSON lines: method, orderId and duration_ms go into "fields" and requestId into "context", for jq and log collectors. More in Fields, Context, Wide events, Timing a block and Print debugging.

API at a glance

Every level has the same set of overloads; info below stands for trace, debug, info, warn, error.

Call Meaning
LOG.info(message) any object; its toString() is called safely
LOG.info("... {} ...", args) parameterized message, see Message formatting
LOG.info(() -> message) lazy message, evaluated only if the level is enabled
LOG.debug("Stats: {}", LOG.lazy(() -> summarize(stats))) one lazy argument: computed only if the level is enabled, and the template stays a template, see Message formatting
LOG.info(throwable) stack trace without a message
LOG.info(throwable, message) message plus stack trace; the message may also be a Supplier
LOG.info(throwable, "... {} ...", args) exception plus a parameterized message
LOG.info("... {} ...", args, throwable) the SLF4J order: a trailing exception that no {} consumes becomes the exception of the entry
LOG.info("Payment accepted", LOG.kv("orderId", id)) a named argument: orderId=A-17 after the message, a field in JSON; in a {} it prints its value, see Fields
LOG.info("Login with {}", LOG.secret(token)) a secret written as *** by every logger; fields and context named like secrets are masked too, see Masking secrets
LOG.debug("Prompt: {}", LOG.content(prompt)) a payload written as its length and hash unless nanolog.content shows it, see Logging payloads safely
LOG.info(SomeClass.class, ...) any form above with an explicit source class
LOG.isInfoEnabled() level check, with or without an explicit class
LOG.setLevel(level), LOG.setLevel("com.acme", level) change the global level or the level of a package while the application runs, see Changing levels at run time
LOG.withLevel("com.acme", level) the same for a try block, restored at its end
LOG.dbg(expression) print the expression, its value and the call site, and return the value, see Print debugging
LOG.once().warn(...) log a statement only the first time it runs, see Rate limiting
LOG.atMostEvery(10, TimeUnit.SECONDS).warn(...) at most once per period, with the number of skipped calls on the next entry
try (LOG.Timer t = LOG.time("Load users")) Load users took 123 ms when the block ends; LOG.timed("Count", () -> repo.count()) returns the value, see Timing a block
try (LOG.Unit u = LOG.unit("checkout")) one line when the unit closes: name, outcome, duration, fields and the counts of warnings and errors inside, see Wide events
LOG.unit("import", () -> importer.run()) the same for a lambda: a thrown exception fails the unit and is thrown on
LOG.unit(WARN, "sync", () -> client.sync()) a failed unit writes WARN instead of ERROR, for failures that are expected
try (LOG.Context c = LOG.context("requestId", id)) adds requestId=... to every entry the thread logs until the block ends, see Context
LOG.addContextProvider(() -> ids) adds the keys of a context of its own, such as the trace ID of OpenTelemetry, to every entry, see Context providers
LOG.tag("audit").info(...) an entry of a concern rather than of a class, with levels per tag in nanolog.tags, see Tags
executor.submit(LOG.wrap(task)) runs the task with the context of the code that submitted it
LOG.catching(() -> connection.close()) run an action, log an exception at ERROR and carry on; LOG.catching(() -> parse(s), -1) returns a default, see Catching exceptions
LOG.captureSystemStreams() turns the lines printed to System.out and System.err into entries, see System.out and System.err
LOG.installUncaughtExceptionHandler() log the exceptions that kill threads, then pass them to the previous handler
LOG.log(level, sourceClass, throwable, supplier, args) the universal entry point every overload delegates to

Every class and method is documented in the Javadoc, which IDEs also show from the sources jar.

Fewer tokens: logs for AI coding agents

Since 1.4.

A coding agent pays for every token of output it reads, and a test run competes with the code for its context window. When an agent runs the program, Nanolog switches to agent mode and keeps the console short. The table counts what mvn -q test printed for the same runs of a small project, first without agent mode, then as Claude Code runs them (AI_AGENT=claude-code):

Run Lines Tokens, o200k_base
A test logs 200 orders and fails; the error has a cause 558 → 43 13,577 → 1,058 (12.8×)
A green test of a job that logs INFO and DEBUG for each of 300 records 602 → 2 16,550 → 178 (93×)
A green test whose retry loop logs the same WARN 300 times 301 → 5 9,925 → 259 (38.3×)
A test fails with an exception thrown inside a stream pipeline 120 → 45 2,427 → 1,052 (2.3×)

Measured on 2026-11-19 on Windows 10, JDK 8, Maven 3.9 and Surefire 3.2.5, with the default settings. The counts include everything Maven printed, Surefire's report of a failure too, and agent mode leaves that report as it is; that is why the last run saves the least. o200k_base is the tokenizer of OpenAI's GPT-4o and later models; Claude tokens have not been counted yet. The project, the script and the full table with character counts are in src/tokens (RESULTS.md): python src/tokens/measure.py repeats the runs, and counts Claude tokens as well when an Anthropic API key is set.

👀 Picture: the failing run takes 558 lines without agent mode and 43 with it

The failing test run side by side: without agent mode 558 lines and 13,577 tokens, of which the first 62 lines fit the height of the picture; in agent mode the whole run, 43 lines and 1,058 tokens, run summary included

Both panels have the same font and height. The picture is drawn from the saved output of the run by src/tokens/before-after.py, which also counts the lines and tokens it shows.

Where the tokens go:

  • The console keeps WARN and above in agent mode, and the run log every level: a green run prints one line about agent mode and the run summary. See Agent mode.
  • One line per entry, without the date and colours: line breaks inside an entry are written as \n.
  • Repeats collapse. A line repeated by a loop or a retry is printed once, then as (repeated 299 more times in 53 ms).
  • Short stack traces. Frames of the JDK, test runners, build tools and frameworks collapse, at most 20 frames per throwable are printed, and every cause is kept. See Shorter stack traces.
  • A summary instead of another run. The run ends with the counts and the first error, and latest.log holds the rest, so the agent reads a file instead of running again with another level. See Run summary and Run log.
  • Fewer lines from the code itself. LOG.once() and LOG.atMostEvery(...) thin out loops and polls, and LOG.content(...) writes a prompt or a response as its size and hash. See Rate limiting and Logging payloads safely.

Try agent mode on a failing test

Run these commands separately from the repository root. Maven takes Nanolog 1.4.1 from Maven Central. Both runs deliberately fail on order 150.

mvn -q -f src/tokens/shop/pom.xml -Dtest=OrderServiceTest "-Dtokens.version=1.4.1" "-Dnanolog.agent=off" test
mvn -q -f src/tokens/shop/pom.xml -Dtest=OrderServiceTest "-Dtokens.version=1.4.1" "-Dnanolog.agent=on" test

The first run shows the progress of the batch in the console. In the second, look for Run summary and the path to the log file that holds all Nanolog entries.

If you run this demo or try agent mode on your own tests, tell us whether the summary helped you find the cause of a failure. A line or two is enough.

Agent-driven development

When a coding agent (Claude Code, Codex, Copilot and others) writes and debugs the code,
one short loop repeats many times: edit, run, read the output, edit again.
Nanolog keeps every step of that loop cheap.

Nanolog detects coding agents. When an agent runs the program, the console keeps what the agent needs: WARN, ERROR and LOG.dbg, one line per entry, without dates and with short stack traces, and every entry still goes to target/nanolog/latest.log. See Agent mode.

  • One line to add logging. No logger field and no getLogger(Foo.class) that has to match the class name: one import and LOG.info(...). Nothing goes stale when the code is moved or the class is renamed.
  • Output from the first run. ConsoleLogger works without configuration and prints every level, TRACE included; in agent mode the console keeps WARN and above, and the run log every level. A LOG.debug(...) added while investigating a problem is visible in the very next run, with no backend to set up first.
  • Levels per run, without code. NANOLOG_LEVEL=INFO cuts the noise once the first run is read, and -Dnanolog.level.com.acme.payments=DEBUG turns detail up for one package, even if the startup code switched DEBUG off. Agents in sandboxes and CI can always set an environment variable; a temporary code edit tends to get committed. A mistyped setting is reported with the key it was probably meant to be, so a wrong name does not pass for a working one. See Levels and options without code.
  • Lines that are easy to read back. One entry is one line of the form LEVEL date [SourceClass] message, followed by the stack trace if there is one. A message with line breaks would break that rule. nanolog.console.multiline=escape keeps every entry, its stack trace included, on one physical line, and indent starts every further line of an entry with a tab, so user data cannot forge an entry. Agent mode uses escape. The output is simple to grep and to match against the sources. With setShowLocation(true) every line also names the method and the line of the call, [PaymentService.charge(PaymentService.java:87)], so the agent jumps from the output straight to the statement. Through SLF4J, the backend's own %file:%line reports the same call site.
  • Output a script can parse. -Dnanolog.logger=com.nanolaba.logging.JsonLogger switches to one JSON object per line, with the timestamp, thread, call site and stack trace as fields, ready for jq or a script the agent writes on the fly. See JsonLogger.
  • SLF4J habits carry over. The same {} placeholders, and the exception may go first or last: LOG.error("Failed to load {}", id, e) logs the stack trace exactly as SLF4J does.
  • A log call cannot fail the run. Logging never throws: a broken toString(), a lazy message whose lambda throws, a null or a wrong number of {} arguments ends up as a readable message, not as an exception. In test runs, -Dnanolog.strict=true still reports such mismatches with the call site, so they get fixed instead of going unnoticed.
  • Repeated lines do not crowd out the rest. A retry loop or a full queue can print the same line thousands of times and push the line that matters out of the context window. LOG.once() and LOG.atMostEvery(10, TimeUnit.SECONDS) keep such a statement to one line, or to one line per interval, and the next one that gets through says [skipped 241]; see Rate limiting.
  • The whole library fits in a context window. One package of small classes, one entry point, this README and the Javadoc. Every public method has Javadoc, so the IDE and the sources jar give the same answers as this file. An agent reads everything it needs in one pass and does not have to map a framework first.
  • Green tests stay quiet. @ExtendWith(NanologExtension.class) prints the log of a test only when the test fails, framed by its name, so a run of five hundred tests shows the log of the one that broke. See Logs in tests.
  • Capturing the log in a test takes one line. try (MemoryLogger log = MemoryLogger.install()) keeps the entries in memory and puts the previous logger back afterwards, so what was logged is asserted without a mocking framework; see MemoryLogger and CompositeLogger.
  • The end of the output says what happened. In agent mode the run ends with a summary: the counts by level, each kind of warning and error with its call site and count, the trace of the first error and the path of the full log. It survives when the agent keeps only the tail. See Run summary.
  • The last run is kept in a file. In agent mode, or with nanolog.run=on, the run also writes target/nanolog/latest.log, with warnings and errors in latest.errors.log, and prints the path. The agent reads the file instead of running a five-minute suite again for every grep, and follows a background server with tail -f. See Run log.
  • Debug prints do not stay behind. A forgotten System.out.println looks like any other output; a LOG.dbg call has a name of its own. The run lists the ones that printed, nanolog.dbg=off silences them in production, and NanologChecks.assertNoDbgCalls fails a test while one is left in the sources, with the file and line the agent has to fix. See Leftover calls.
  • The repository itself is ready for agents. AGENTS.md describes the build, the invariants and the test requirements (JUnit plus 100% mutation coverage), so an agent can fix and extend Nanolog, not only use it.

Agent mode: Nanolog detects coding agents

Since 1.4.

Coding agents read program output through a narrow window: a long output is cut down to its head and tail or summarised, and agents rarely ask for the rest. When the environment names a coding agent, Nanolog keeps its own console short and writes the full log to a file.

A test that logs 200 orders and fails on order 150 prints this under Claude Code:

[NANOLOG] Agent mode (AI_AGENT=claude-code): the console shows WARN, ERROR and every LOG.dbg; the full log is in /home/me/shop/target/nanolog/runs/20261117-101502-311-4821.log, WARN and ERROR also in /home/me/shop/target/nanolog/runs/20261117-101502-311-4821.errors.log; nanolog.agent=off turns it off
WARN [OrderService] Order 150: stock of SKU A-7 below the threshold
ERROR [OrderServiceTest] The batch failed java.lang.IllegalStateException: Cannot reserve stock for order 150\n	at com.acme.shop.OrderService.reserve(OrderService.java:32)\n	at com.acme.shop.OrderService.process(OrderService.java:20)\n	at com.acme.shop.OrderServiceTest.processesTheDailyBatch(OrderServiceTest.java:16)\n	... 71 frames excluded\nCaused by: java.sql.SQLException: Deadlock found when trying to get lock; order 150\n	at com.acme.shop.OrderService.update(OrderService.java:38)\n	at com.acme.shop.OrderService.reserve(OrderService.java:30)\n	... 73 more

The run then ends with the run summary.

Without agent mode the same run printed 530 lines of Nanolog output: three lines per order with dates, then the stack trace with every frame of JUnit, Surefire and reflection. The whole mvn -q test output went from 558 lines, 39,355 characters and 13,577 tokens to 43 lines, 3,843 characters and 1,058 tokens, the run summary included (JDK 8, Maven 3.9, Surefire 3.2.5, on Windows, with long absolute paths), and latest.log still holds all 451 entries. The project of this example is in src/tokens; Fewer tokens has three more runs.

  • Detection. Agent mode is on when one of these variables is set to anything but 0, false, no or off: AI_AGENT and AGENT, the convention proposed in agents.md #136, then CLAUDECODE, GEMINI_CLI, CODEX_SANDBOX, CODEX_CI, CURSOR_AGENT, VSCODE_AGENT and CLINE_ACTIVE. Claude Code, for one, sets AI_AGENT and CLAUDECODE. Environment variables are lost across sudo, docker run and ssh, so detection is a hint: nanolog.agent=on or off (NANOLOG_AGENT) decides instead.
  • The console. WARN and above, unless nanolog.level or a package rule says otherwise. One line per entry, with line breaks written as \n, a Windows line separator as \r\n (nanolog.console.multiline=escape), no date and no colours, and consecutive repeats collapsed into one line with a count (nanolog.console.repeats=collapse), unless these settings are given. Stack traces collapse runs of frames of the JDK, Kotlin, test runners, build tools and common frameworks and servers (Spring, Tomcat, Jetty, Netty, Hibernate), print at most 20 frames per throwable and keep every cause; nanolog.exception.exclude and nanolog.exception.maxFrames replace these defaults.
  • LOG.dbg prints whatever the levels: the agent put it there to see the value. With Slf4jLogger or JulLogger, a LOG.dbg line that the backend would drop, its class having DEBUG off there, is printed by Nanolog on System.out in the format of the console above. nanolog.dbg=off still silences it.
  • The run log is on and keeps every level, the date, the thread, the call site and the whole stack trace, so the agent reads it instead of running again with another level; nanolog.run=off turns it off. See Run log.
  • One line says what happened, once per JVM, before the first entry: what turned agent mode on, what the console shows and where the full log is. A logger that the application installs with LOG.init(logger) before it logs is named instead of the console, with its call site: com.nanolaba.logging.ConsoleLogger installed at com.acme.Tool.main(Tool.java:5) keeps its own levels and format. A run that logs nothing prints no such line. The value of the variable is shown up to 64 characters, then cut with ... [+4936 chars], and in double quotes when it would not read as one value: anything in the process tree may set it, and the agent reads the line.
  • The run ends with a summary: see Run summary; nanolog.summary=off turns it off.
  • Only Nanolog's own output changes. The defaults above apply to the default logger, ConsoleLogger or JsonLogger; a logger set with LOG.init(logger), or another class named by nanolog.logger, keeps its settings. The levels do not change either: LOG.isDebugEnabled() and the lazy arguments of a call answer as without agent mode, so code that checks a level behaves the same under an agent. A test that reads what the default logger prints to the console sees less under an agent: capture the entries with MemoryLogger, or set NANOLOG_AGENT=off for the test JVM (environmentVariables of Surefire).
  • A command-line tool whose output a program or an agent reads, a hook of Claude Code for one, gets nothing it did not log: the line of agent mode and the files of the run log come with the first entry, and a run that logged nothing prints no summary. A tool that logs and wants none of agent mode sets System.setProperty("nanolog.agent", "off") as the first statement of main, or NANOLOG_AGENT=off in its launcher. Once LOG has initialised, the same property and then LOG.init(), before the tool logs or installs its logger, turn agent mode off for the rest of the run, the run log included.
  • Turned off in the middle of the run, after the line of agent mode has named the run log, agent mode says so: one line on the console and last in both files names the LOG.init() call that read the setting, [NANOLOG] Agent mode turned off by LOG.init() at com.acme.ToolTest.setUp(ToolTest.java:14) (nanolog.agent=off): the run log ends here, after 2 entries, so the end of latest.log does not read as a crash, and the run summary still ends the run with the entries before that call. In a test JVM, a test that sets nanolog.agent=off and does not put it back turns agent mode off for every later test; the line names the LOG.init() that read it.

Run summary: the part of the output that survives truncation

Since 1.4.

A coding agent often sees only the start and the end of a long output. Claude Code shows a failing command as an excerpt of its head and tail, about 10,000 characters (tools reference); Cursor cuts the output of a command at 20,000 characters (forum); agents add | tail -30 themselves and rarely ask for the rest (Agents Don't Paginate). The error that matters is often in the part that was dropped. Nanolog prints a summary of the run last, where it survives.

[NANOLOG] Run summary: 451 entries: 1 ERROR, 1 WARN, 150 INFO, 299 DEBUG; the full log is in /home/me/shop/target/nanolog/runs/20261117-101502-311-4821.log
[NANOLOG]   ERROR x1 at OrderServiceTest.java:19: The batch failed
[NANOLOG]       java.lang.IllegalStateException: Cannot reserve stock for order 150
[NANOLOG]           at com.acme.shop.OrderService.reserve(OrderService.java:32)
[NANOLOG]           at com.acme.shop.OrderService.process(OrderService.java:20)
[NANOLOG]           at com.acme.shop.OrderServiceTest.processesTheDailyBatch(OrderServiceTest.java:16)
[NANOLOG]           ... 71 frames excluded
[NANOLOG]       Caused by: java.sql.SQLException: Deadlock found when trying to get lock; order 150
[NANOLOG]           at com.acme.shop.OrderService.update(OrderService.java:38)
[NANOLOG]           at com.acme.shop.OrderService.reserve(OrderService.java:30)
[NANOLOG]           ... 73 more
[NANOLOG]   WARN x1 at OrderService.java:27: Order {}: stock of SKU A-7 below the threshold

In the failing mvn -q test run of the agent mode example these 12 lines end 14 lines before the end of the output, after Surefire has printed the failure, so tail -30 keeps them.

  • What. The number of entries by level; each kind of warning and error, by level and call site, with how often it was logged, errors first: a call site that builds its messages from data, "Merge of #" + id + " failed", is one kind with its first message and (4 different messages), and a call with an explicit class, which has no call site, is told apart by its message; a message of several lines shows its first line, followed by ...; the stack trace of the first error with an exception, without the frames of agent mode and with every cause; the LOG.dbg calls that ran; the path of the run log. It counts the entries that reach the logger: a warning that a test provokes inside MemoryLogger.capture(), which keeps it from the logger, is neither in the summary nor in the run log.
  • Bounded. At most 10 kinds and 15 lines of the trace are shown; the rest is counted (... and 7 more kinds of WARN and ERROR), unless it is a single kind or line, which is shown in the place its count would take. Counting keeps no entry, only a counter per level and per kind, for at most 1000 kinds, and costs nothing while the summary is off.
  • Every kind in a file. With the run log on, the summary also writes every kind it counted to runs/<time>-<pid>.summary.log, one line each as above, ordered by level and call site rather than as the run went, so the lists of two runs can be compared with diff. When kinds are left out, the line that counts them names the list: ... and 7 more kinds of WARN and ERROR; the full list is in /home/me/shop/target/nanolog/latest.summary.log. latest.summary.log is a second name of the list of the run in latest.log, once that run has ended; a JVM in which Surefire, Failsafe or Gradle runs tests names its own list, as it names its own log. Since 1.4.1.
  • When. nanolog.summary=on (NANOLOG_SUMMARY), the default in agent mode; errors prints it only after a WARN or ERROR; off, the default otherwise. It goes to System.err once per JVM: when JUnit has run the tests of that JVM, through SummarySessionListener and SummaryListener, which the JUnit Platform loads by itself in Maven, Gradle and the IDE; otherwise when the JVM exits, also in a Maven plugin, whose class loader Maven closes before that. A Surefire fork that runs several test classes, with forkCount above 1, prints one summary after the last of them, in one piece, so the summaries of two forks that end together do not mix. Surefire drops what a shutdown hook of its forked JVM prints, which is why test runs need the listeners. Gradle prints the output of tests only with testLogging.showStandardStreams = true. A run that logged nothing prints no summary. A LOG.init() that turns the summary off after it has counted, by turning agent mode off for one, stops the counting, and the end of the run still sums up what was counted before, with the run log that holds it: Run summary until LOG.init() at com.acme.ToolTest.setUp(ToolTest.java:14) turned it off: 2 entries: 1 ERROR, 1 WARN; ....
  • A jar of your own. SummaryListener and SummarySessionListener are compiled against the JUnit Platform Launcher API, which a test run provides, so Nanolog still has no dependencies. A shaded jar that keeps META-INF/services/org.junit.platform.launcher.TestExecutionListener or org.junit.platform.launcher.LauncherSessionListener must keep the class it names too, or JUnit stops with a ServiceConfigurationError.

Run log

Since 1.4.

With nanolog.run=on (NANOLOG_RUN=on) every entry of the run also goes to a file at a predictable place. A coding agent reads the output of the last run there instead of running the program again with another filter, and follows a server that runs in the background. Off by default, on in agent mode.

[NANOLOG] Run log: /home/me/shop/target/nanolog/latest.log; WARN and ERROR also in /home/me/shop/target/nanolog/latest.errors.log
  • Where. target/nanolog in a Maven module, build/nanolog in a Gradle one, .nanolog otherwise, which gets a .gitignore; nanolog.run.dir names another directory. The absolute path is printed with the first entry, because search tools often skip ignored *.log files.
  • What. latest.log holds every entry, with the thread and the call site; nanolog.run.format=json writes the lines of JsonLogger instead, ready for jq. latest.errors.log holds each WARN and ERROR as one line, cheap to follow with tail -f, written as nanolog.console.multiline=escape writes it, so a logged value cannot act on the terminal. Both files, read back by agents, escape the bidi controls and tags described there, also when latest.log keeps line breaks. With the run summary on, latest.summary.log lists every kind of warning and error of the run at its end, see Run summary.
  • History. Each run writes runs/<time>-<pid>.log, and latest.log is a second name of the newest one, a hard link, so it shows the run live and is written once. The last 10 runs are kept (nanolog.run.keep); a file stops at 100 MB with a note (nanolog.run.maxSize). Where hard links are not supported, or once a later run in the same directory has taken latest.log, the path of the run's own file is printed instead of latest.log, in the run summary as well. A JVM in which Maven Surefire or Failsafe or Gradle runs tests prints the path of its own file from the start: several of them may run in one module, side by side (forkCount above 1) or one after another (reuseForks=false), and each takes latest.log from the one before, so each fork names the file with its own entries.
  • Levels. The run log reads nanolog.level and the package rules as ConsoleLogger does, and LOG.setLevel changes both. It takes what the logger takes, so LOG.isDebugEnabled() and the lazy arguments of a call answer as they would without it: a logger installed with LOG.init(logger) or named by nanolog.logger, Slf4jLogger for one, decides the levels of the file too. Only the short console of agent mode leaves the rest to the file, which keeps the levels the console has without agent mode.
  • Safe. An entry is on disk as soon as it is logged, even if the JVM is killed. An I/O error prints one [NANOLOG] line and turns the run log off; logging goes on. The files are opened once per JVM, with the first entry, so a run that logs nothing leaves those of the run before alone: LOG.init() keeps writing them, and so does a logger installed with LOG.init(logger) or MemoryLogger.install(), Spring's Slf4jLogger for one: the run log is added to it, and LOG.getLogger() returns a CompositeLogger of both. A decorator that passes each entry on to the logger LOG.getLogger() returned, and MemoryLogger.installForwarding(), write each entry to the file once. A LOG.init() whose settings no longer turn the run log on, nanolog.agent=off without nanolog.run=on, stops it for the rest of the JVM; once its files are open, a last line in both and on the console says so, [NANOLOG] Run log turned off by LOG.init() at com.acme.Tool.main(Tool.java:9) (nanolog.run=off): it ends here, after 2 entries, or Agent mode turned off by ... when agent mode ended it.

Using Nanolog from a coding agent

Two files give an agent the rules of the library in a few hundred lines, without the explanations of this README:

  • llms.txt — a cheat sheet in the llms.txt format: coordinates, call shapes, the rules that differ from SLF4J, settings without code changes and the test recipe.

  • skills/nanolog/SKILL.md — the same guide as an agent skill, which the agent loads by itself when it works on code that logs through Nanolog. Install it in one of three ways:

    • Claude Code, as a plugin that stays up to date:

      /plugin marketplace add nanolaba/nanolog
      /plugin install nanolog@nanolog
      
    • Claude Code, Cursor, Codex and the other agents that read Agent Skills, with the skills CLI (-a claude-code limits it to one agent):

      npx skills add nanolaba/nanolog
      
    • By hand, into the project:

      mkdir -p .claude/skills/nanolog
      curl -fsSL https://raw.githubusercontent.com/nanolaba/nanolog/main/skills/nanolog/SKILL.md -o .claude/skills/nanolog/SKILL.md
      

      Other agents that support the Agent Skills format read the same file from their own skills directory.

Both files also tell the agent what to do when Nanolog itself misbehaves: report it to you, with a link to the issue forms and what to include, and never open an issue on its own. In a project without Nanolog the skill may suggest it, but never adds the dependency without your consent.

Or skip the installation: a few lines in AGENTS.md (or CLAUDE.md) of the project are enough:

## Logging

This project logs with Nanolog (com.nanolaba:nanolog). Before adding or changing log calls,
read https://raw.githubusercontent.com/nanolaba/nanolog/main/llms.txt

For temporary debug output use LOG.dbg(...), never System.out.println, and remove every
LOG.dbg call before you finish: the test with NanologChecks.assertNoDbgCalls must pass.

Both files are generated from agent-guide.src.md on every build: the versions come from pom.xml, the code
from the compiled examples, and CI fails when they are stale. Ideas for making the library easier for agents
are collected under the agents label.

Print debugging: LOG.dbg prints the expression and its value

Since 1.4.

LOG.dbg(...) is the Java counterpart of Rust's dbg! and Python's icecream: it prints the expression as written in the source, its value and type, and the file and line of the call, and returns the value, so it wraps any expression in place.

BigDecimal total = LOG.dbg(order.total());   // prints, then returns the value
LOG.dbg(user, cart.size());
LOG.dbg();                                   // prints "reached"
DBG 17.11.2026 10:15:02 [PrintDebugging.checkout(PrintDebugging.java:21)] order.total() = 129.90 (BigDecimal)
DBG 17.11.2026 10:15:02 [PrintDebugging.checkout(PrintDebugging.java:22)] user = "alice", cart.size() = 3 (Integer)
DBG 17.11.2026 10:15:02 [PrintDebugging.checkout(PrintDebugging.java:23)] reached
  • The text comes from the source file of the call site. The source directory is derived from where the class was loaded: target/classes leads to src/main/java, target/test-classes to src/test/java, Gradle's build/classes/java/main to src/main/java, and the same for Kotlin; for other layouts the usual directories of the working directory are tried. nanolog.sources=dir1,dir2 names them explicitly. Each call site is read once, arguments spread over several lines included.
  • Without the text only the values are printed, never an error: when no source directory is found (a production jar), the source file is newer than its class, or the line holds two dbg calls, since Java reports the line of a call but not its column.
  • Strings and chars are quoted and escaped, so a value never breaks the line; collections, maps and arrays are printed item by item, objects without a toString() of their own field by field (see below); other values are followed by their type, unless their text starts with it, as Invoice{id=17, ...} does.
  • It is a DEBUG entry: nanolog.level and package rules apply, and a level that is off everywhere costs no stack walk. In agent mode it prints whatever the levels; when Slf4jLogger or JulLogger would pass it to a backend that has DEBUG off for the class, the console of Nanolog prints it instead. ConsoleLogger marks it DBG and prints the call site even without showLocation, JsonLogger adds "dbg":true, any logger tells it apart with LogEntry.isDbg(). LOG.once().dbg(...) and LOG.atMostEvery(...).dbg(...) limit it like any other statement.
  • dbg is meant to be temporary: a debug print that names its values replaces a series of System.out.println calls, and its distinct name lets Nanolog find the calls left behind, see Leftover calls.

Rust has had dbg! in its standard library since 1.32 (2019), Python has had f"{x=}" since 3.8 and the icecream package; the JDK has nothing comparable, and an IDE template such as IntelliJ's soutv types the name into the code, where it goes stale on a rename.

Objects without toString()

An object whose class has no toString() of its own is printed field by field, not as Invoice@2f92e0f4. Since 1.4.

// no toString() in any of them
static class Customer {
    String name = "alice";
    String password = "s3cr3t";
}

static class Line {
    String sku;
    int qty;

    Line(String sku, int qty) {
        this.sku = sku;
        this.qty = qty;
    }
}

static class Invoice {
    long id = 17;
    List<Line> lines = Arrays.asList(new Line("A-1", 2), new Line("B-7", 1));
    Customer customer = new Customer();
}

void inspect(Invoice invoice) {
    LOG.dbg(invoice);
}
DBG 17.11.2026 10:15:02 [PrintDebugging.inspect(PrintDebugging.java:52)] invoice = Invoice{id=17, lines=[Line{sku="A-1", qty=2}, Line{sku="B-7", qty=1}], customer=Customer{name="alice", password=***}}
  • A class with a toString() of its own keeps it and is never reflected into. Classes of the JDK are never reflected into either: collections, maps, arrays and Optional are walked through their public API, any other JDK value prints its toString(). So the dump needs no --add-opens on JDK 17+ and cannot fail with InaccessibleObjectException, unlike Commons Lang ReflectionToStringBuilder. A field that cannot be read prints <inaccessible>.
  • The fields of superclasses come first; static and synthetic fields are left out. A record prints its components, Point[x=1, ys=[2, 3]], with arrays element by element, which its generated toString() does not do.
  • Every limit says what it left out: an object met again inside itself prints <cycle: Invoice>; a container more than three levels below the printed value prints Customer{... (+2 more)}; a collection, map or array shows at most 100 items, then ... (+900 more); a string inside a dump shows at most 1000 characters, then ... (+24 more chars). A string passed to dbg itself is never cut.
  • A field or a string map key whose name contains password, passwd, secret, token, apiKey, credential or authorization, ignoring case, _ and -, prints *** unless it is null, so accessToken and X-Api-Key are hidden too.
  • Proxies and lambdas print only their class name: a Hibernate proxy ($HibernateProxy$), a CGLIB or Javassist class ($$) or a java.lang.reflect.Proxy is never called, so printing an entity never triggers lazy loading.
  • Nothing escapes: a failure while dumping a value prints [FAILED dump()], as a broken toString() prints [FAILED toString()].

The same dump is available for {} arguments of every log call with nanolog.dump=auto, see Message formatting.

Leftover calls

dbg is meant to be temporary, and debug prints are easy to leave behind, by people and coding agents alike. Nanolog knows its calls by name, so it can find them. Since 1.4.

At the end of the run, when JUnit has run the tests or when the JVM exits, one line on System.err lists the call sites that printed, in the order they first ran; with the run summary on, the line is part of it:

[NANOLOG] 3 LOG.dbg calls ran in this JVM: OrderService.java:87, OrderService.java:88, CartService.java:31

A test in the project fails while the sources still call LOG.dbg and names every call:

@Test
void noDebugPrintsLeft() {
    NanologChecks.assertNoDbgCalls("src/main/java"); // lists the file, line and code of every call
}
java.lang.AssertionError: 2 LOG.dbg calls left in the code; remove them:
src/main/java/com/acme/OrderService.java:87: BigDecimal total = LOG.dbg(order.total());
src/main/java/com/acme/CartService.java:31: LOG.dbg();
  • NanologChecks.assertNoDbgCalls reads the .java and .kt files under the directories as text: no compiler plugin, no annotation processor, no extra dependency. It finds LOG.dbg(...), LOG.once().dbg(...), LOG.atMostEvery(...).dbg(...), LOG::dbg and a static import of LOG.dbg, also split over lines, and skips comments, strings and text blocks, so a Javadoc that shows LOG.dbg does not count.
  • A relative directory resolves against the working directory, which is the module directory in Maven and Gradle test runs. A directory that does not exist fails the test instead of passing it with nothing checked.

nanolog.dbg (NANOLOG_DBG) decides what the calls do at run time:

nanolog.dbg Calls
on print; the default
off print nothing and cost one check, before any stack walk; for production
fail still print and return their value, and each one is reported as a diagnostic

With fail, each call site prints one line on System.err, and every call reaches the logger through ILogger.onDiagnostic, so MemoryLogger.assertNoDiagnostics() fails, as with strict mode. Nothing is thrown:

[NANOLOG] com.acme.OrderService.checkout(OrderService.java:87): LOG.dbg call left in the code (nanolog.dbg=fail)

Like the entries themselves, the list at exit and the reports cover only calls whose DEBUG level is enabled; the test above finds every call.

Wide events: one line per request (canonical log lines)

Since 1.4.

Dozens of scattered lines per request are hard to read, for people and for agents alike. The idea of wide events and of canonical log lines at Stripe is one rich line per request or job. LOG.unit(name) writes that line when the unit of work ends, next to the usual log, not instead of it:

try (LOG.Unit u = LOG.unit("checkout")) {
    u.put("orderId", orderId).put("items", items.size());
    charge(orderId); // logs as usual; its warnings and errors are counted
}
// INFO 16.11.2026 10:15:02 [CheckoutService] checkout ok 182 ms orderId=A-17 items=3 warn=1

LOG.unit("import", () -> importFile(file)); // an exception fails the unit and is thrown on
// ERROR 16.11.2026 10:15:03 [CheckoutService] import error 41 ms error.type=java.io.UncheckedIOException ...
  • The line is <name> <outcome> <duration> ms, then the fields of put(...) and the counts of warnings (warn) and errors (error) logged inside the unit, in any thread it was carried into. Its fields are unit, outcome, duration_ms and the rest, so JsonLogger writes "fields":{"unit":"checkout","outcome":"ok","duration_ms":182,...} and jq selects the failed units by .fields.outcome.
  • The outcome is ok, an INFO line, or error, an ERROR line, once an ERROR entry was logged inside the unit or fail(e) was called. A failed unit adds error.type, error.message and error.key: eight hexadecimal digits made from the template and call site of the first error, the same in every run, so failures of one kind can be counted. LOG.unit(WARN, "sync"), since 1.4.1, writes the line of a failed or interrupted unit at another level, for work whose failures are expected and handled elsewhere, a job that is retried or a call to a service that is often down, where every ERROR would raise an alert: ok stays INFO, and the outcome, the counts and the error.* fields do not change, so outcome=error still finds the unit.
  • Exceptions. close() cannot see an exception that leaves a try-with-resources block: catch it and call u.fail(e), or let run(...) do it. LOG.unit("import", () -> importFile(file)) and LOG.unit("report").put("month", m).run(() -> build(m)) mark the unit failed, attach the exception to its line and rethrow it.
  • Nesting. A unit opened inside another names it as parent, and an entry counts in every unit around it. LOG.wrap(task) carries the open unit into a task for an executor together with the context, so the tasks of a request count in its unit.
  • Not lost. A unit still open when its thread dies of an uncaught exception, with LOG.installUncaughtExceptionHandler(), or when the run ends (the JVM exits or JUnit has run the tests) is written with the outcome interrupted. That happens before the run summary, which therefore counts it and lists a failed unit as unit <name>.
  • Sampling. nanolog.unit.sample=0.05 writes 5% of the units that succeed fast and every failed one, and nanolog.unit.slowMs=500 always writes those that take 500 ms or longer. By default every unit is written.
  • Levels. The line has the source class and call site of the LOG.unit call (for Logback and Log4j 2, see Slf4jLogger) and the context of the thread. It follows the levels: an ok unit of a class set to WARN writes nothing, a failed one is still written, unless LOG.unit(level, name) gave it a level that is off too. In agent mode the console shows only the failed units, and the run log has them all.
  • Breadcrumbs. With nanolog.buffer=DEBUG a failed unit is followed by the DEBUG entries logged inside it, and a successful one drops them; see Breadcrumbs.
  • Cost. A unit costs one stack walk, to find where it was opened, and one line. Code outside units pays nothing beyond the ThreadLocal read of the context.

Timing a block

Since 1.4.

"Which step is slow?" usually means two System.nanoTime() calls and a subtraction, written again each time. LOG.time(name) writes one uniform line that a person or an agent can compare between runs:

try (LOG.Timer t = LOG.time("Load users")) {
    users = repository.loadAll();
}
// INFO 16.11.2026 10:15:02 [UserService] Load users took 123 ms

int count = LOG.timed("Count users", () -> repository.count()); // returns the value
LOG.time(LogEntry.LogEntryLevel.DEBUG, "Parse").close();         // another level; INFO by default
  • The line has the fields timer and duration_ms, as a unit of work has its duration_ms, so JsonLogger writes "fields":{"timer":"Load users","duration_ms":123}. Its source class and call site are those of the LOG.time call; for the %file:%line of Logback and the %l of Log4j 2, see Slf4jLogger.
  • A level that is off for the class reads no clock and writes nothing, so a timer can stay in a hot path. The timer uses the clock of atMostEvery, which tests replace.
  • LOG.timed(name, body) writes Count users failed after 12 ms with the stack trace when the body throws, and rethrows the exception; close() of a try-with-resources block cannot see an exception. For a request or a job with an outcome and fields, use a unit of work.

Breadcrumbs: DEBUG only when something fails

Since 1.4.

With DEBUG off the log lacks the context of a failure, and with DEBUG on it drowns. nanolog.buffer=DEBUG keeps DEBUG and TRACE entries in memory and writes them only when an ERROR follows, before the error, as the log buffering of .NET, AWS Powertools and the breadcrumbs of Sentry do:

java -Dnanolog.buffer=DEBUG -jar app.jar
INFO  [Checkout] Checkout of A-17 started
DEBUG --- 3 earlier DEBUG entries ---
DEBUG [Cart] Loaded 3 items
DEBUG [Pricing] Discount SPRING10 applied
DEBUG [Payment] Card ends with 4242
ERROR [Payment] Charge failed
  • The level is TRACE, DEBUG, INFO or WARN, and the levels below it are held back too; off is the default. nanolog.buffer.size=200, the default, keeps the newest entries, and the header says how many older ones were dropped.
  • Held-back levels count as enabled: LOG.isDebugEnabled() is true and the message is built even when the logger has DEBUG off, as with nanolog.level=INFO in production. Building messages that are mostly thrown away costs what logging at DEBUG costs.
  • Outside units each thread has its own buffer, which its next ERROR writes. Inside a unit the unit has the buffer: a successful unit drops it, a failed or interrupted one writes it after its line. In a thread pool open a unit per task, or the buffer of a thread mixes its tasks.
  • An entry is held back as a snapshot: its arguments, fields and context are rendered to text when it is logged, while numbers, booleans and strings keep their type, and text over 2000 characters is cut. Its time, thread and call site stay those of the call: the console prints the time of the call, and JsonLogger adds "breadcrumb":true.
  • LOG.dbg is never held back, and a capture of MemoryLogger gets every entry at once. The buffer sits in front of the installed logger, so the run log too gets the held-back entries only before an error.
  • The run summary counts an entry once, when it is logged. The buffer of a thread that ends without an error is dropped, as is everything held back when the JVM exits normally; a thread that dies of an uncaught exception writes its buffer before the exception, with LOG.installUncaughtExceptionHandler().

Choosing a logger

The default ConsoleLogger can be replaced in three ways:

  1. Programmatically — pass any ILogger implementation to LOG.init(...) at application startup:

    LOG.init(new Slf4jLogger());
    
  2. Via a system property — the fully qualified name of a class with a public no-arg constructor:

    -Dnanolog.logger=com.nanolaba.logging.Slf4jLogger
    
  3. Via a configuration file — put nanolog.properties on the classpath:

    nanolog.logger=com.nanolaba.logging.Slf4jLogger
    

    When LOG initialises, the keys of the file with the nanolog. prefix are copied
    into system properties without overwriting the ones already set via -D or an environment variable.
    Other keys are ignored, and each one is reported (see below). The file path can be overridden with the nanolog.config property.
    The first file in the order of the classpath is read; when there are several and one of them is in a jar, shipped by a library, one [NANOLOG] line lists them all and names the one that was read.
    In tests a nanolog.properties in src/test/resources replaces the one in src/main/resources: Maven and Gradle put the test resources first on the test classpath.
    The whole file is replaced, not merged, so repeat in it the keys the tests still need; a single setting is easier to change with -D or an environment variable, for example in the systemPropertyVariables of Surefire.

Every property can also be set as an environment variable: upper case, dots replaced by underscores, so nanolog.logger becomes NANOLOG_LOGGER.
Precedence, highest first: LOG.init(logger) → -Dnanolog.logger → NANOLOG_LOGGER → nanolog.properties → ConsoleLogger.
A no-argument LOG.init() re-reads the property and the file.

Property Meaning Default
nanolog.logger.lock true keeps the logger of the configuration: later LOG.init calls are ignored with a [NANOLOG] line, as after LOG.lock() false
nanolog.logger class name of the ILogger implementation com.nanolaba.logging.ConsoleLogger
nanolog.config classpath resource with the configuration nanolog.properties
nanolog.sources source directories that LOG.dbg reads the text of its arguments from, comma-separated; empty turns the reading off derived from the class location
nanolog.dbg off silences LOG.dbg, fail reports each call as a diagnostic, see Leftover calls on
nanolog.agent auto detects a coding agent from its environment variables, on and off decide instead, see Agent mode auto
nanolog.junit.output which logs of tests NanologExtension prints: failed, all or none, see Logs in tests failed
nanolog.summary on prints a summary at the end of the run, errors only after a WARN or ERROR, see Run summary off, in agent mode on
nanolog.run on also writes every entry of the run to latest.log, see Run log off, in agent mode on
nanolog.run.dir the directory of the run log, relative to the working directory target/nanolog, build/nanolog or .nanolog
nanolog.run.format text or json text
nanolog.run.keep how many runs the run log keeps, this one included 10
nanolog.run.maxSize the size in megabytes at which a file of the run log stops, with a note 100
nanolog.unit.sample the share of fast successful units that are written, from 0 to 1; failed and slow units are always written, see Wide events 1
nanolog.unit.slowMs the duration in milliseconds from which a unit is slow and always written not set
nanolog.buffer TRACE, DEBUG, INFO or WARN: entries at that level and below are held back and written only before an ERROR, see Breadcrumbs off
nanolog.buffer.size how many entries the buffer keeps per thread or unit, the newest 200
nanolog.redact the words that name a secret, comma-separated: fields and context values whose key, or a word of it, is one of them are written as ***; empty turns masking off, see Masking secrets password,passwd,secret,token,apikey,credential,authorization
nanolog.content how much of a payload of LOG.content(...) is written: hide, truncate:<characters> or show, see Logging payloads safely hide
nanolog.content.<package or class> the same for one package or class; the most specific rule wins —
nanolog.dump auto prints {} arguments field by field when their class has no toString() of its own, see Message formatting off
nanolog.diagnostics how often a [NANOLOG] diagnostic is printed: once per JVM, all every time or off; ILogger.onDiagnostic still gets the findings of strict mode once
nanolog.caller.skip classes and packages, comma-separated, whose frames caller detection skips like those of LOG, see Logging helpers —
nanolog.context.provider classes of context providers, comma-separated, see Context providers —
nanolog.captureSystemStreams true turns the lines printed to System.out and System.err into INFO and ERROR entries, see System.out and System.err false
nanolog.tags levels per tag of LOG.tag(...), comma-separated: audit=WARN,sql=DEBUG; a rule beats the levels of the class, see Tags —
nanolog.strict report calls whose {} placeholders and arguments do not match, whose argument repeats the message of the exception or whose template is built from data, see Message formatting false

If the class named in nanolog.logger cannot be instantiated, Nanolog prints a
[NANOLOG]-prefixed diagnostic to System.err and carries on with ConsoleLogger.

A setting that Nanolog does not know is reported, not ignored without a word. When LOG initialises, each unknown nanolog.* system property, NANOLOG_* environment variable and key of nanolog.properties prints one [NANOLOG] line, with a suggestion when a known key differs by a typo or two:

[NANOLOG] Unknown setting "nanolog.levle" (system property); did you mean "nanolog.level"?
[NANOLOG] Unknown environment variable NANOLOG_LEVEL_COM_ACME; per-package levels go into NANOLOG_LEVELS=com.acme=DEBUG
[NANOLOG] "level" in file:/app/classes/nanolog.properties is ignored: keys must start with "nanolog." (did you mean "nanolog.level"?)

nanolog.buffer.*, nanolog.caller.*, nanolog.console.*, nanolog.content.*, nanolog.context.*, nanolog.exception.*, nanolog.file.*, nanolog.junit.*, nanolog.level.*, nanolog.run.*, nanolog.unit.* and the keys directly under nanolog. belong to Nanolog. A custom logger keeps settings of its own under a namespace of its own, such as nanolog.mylogger.url; such a key is reported only when it differs from a known one by a typo or two. nanolog.version and NANOLOG_VERSION are not reported: a build keeps the version of Nanolog in them, and Surefire passes -Dnanolog.version=1.5 of the Maven command line to the JVMs of the tests as a system property. Since 1.4.

[!IMPORTANT]
LOG.init replaces the logger for the whole JVM. Call it once at application startup, before other threads start logging. Any library on the classpath can call it as well, so do not call it from library code. When code of another organization replaces a logger installed with LOG.init(logger), a [NANOLOG] line names both call sites: Logger replaced: ConsoleLogger (installed at com.app.Main.main(Main.java:12)) -> com.vendor.SdkLogger (installed at com.vendor.Sdk.init(Sdk.java:40)). A call through reflection belongs to the code that made it. A container that installs the logger for the application, as MethodInvokingBean of Spring does, is named in nanolog.caller.skip (org.springframework): its calls count for the application and are never reported. LOG.lock() after your own LOG.init, or nanolog.logger.lock=true for the logger of the configuration, makes later LOG.init calls no-ops with such a line; MemoryLogger.install() still works in tests.

  • The organization is the first two segments of the package of the calling class, com.acme for com.acme.billing.Main: the application and its tests may install their own loggers from anywhere without a line, and anybody may install the same logger again. The logger of the configuration, installed when LOG starts or by LOG.init(), may be replaced without a line as well.

ConsoleLogger

The default implementation. Writes ERROR to System.err and everything else to System.out, one line per entry plus the stack trace:

LEVEL dd.MM.yyyy HH:mm:ss [SourceClass] Message

Every component is controlled by a fluent setter:

LOG.init(new ConsoleLogger()
        .setShowLevel(true)
        .setShowDate(true)
        .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"))
        .setShowSource(true)
        .setShowSourceFullName(false)
        .setShowLocation(false)
        .setShowThread(false)
        .setStream("err@ERROR")
        .setTraceEnabled(false)
        .setDebugEnabled(false));
  • showLevel — the level name.
  • showDate + dateFormat — the timestamp and its SimpleDateFormat; formatting is synchronized, so one shared format is safe.
  • timeZone — the zone of the timestamp, TimeZone.getTimeZone("UTC") for one; the zone of the JVM by default. It is set on the current format and on any format set later. JsonLogger writes UTC whatever the zone.
  • showSource / showSourceFullName — the simple or the fully qualified source class name. An anonymous or local class passed explicitly has no such name and is shown by its binary name, Foo$1 or com.acme.Foo$1.
  • sourceLength — abbreviates the fully qualified name as %logger{n} of Logback does: while it is longer than n characters, the segments of its package, from the left, are cut to their first letter. At 30 com.acme.billing.payments.PaymentService becomes c.a.b.payments.PaymentService, at 20 c.a.b.p.PaymentService; the name of the class is never cut. 0, the default, keeps the full name, and the simple name is never abbreviated. Each class is abbreviated once.
  • showLocation — the call site after the class name, in the form stack traces use, so IDEs and terminals turn it into a link: [PaymentService.charge(PaymentService.java:87)]. Off by default. A call with an explicit source class has no call site and keeps the plain [PaymentService].
  • showSourceLine — the source line of the call on a line of its own under the entry, and under the first three frames of a stack trace outside the JDK, so a reader or an agent need not open the file: > LOG.warn("Charge of {} failed", amount);. It needs the sources, so it works in development: they are found as LOG.dbg finds the text of its arguments, and nothing is written when they are missing or newer than the classes. JsonLogger adds "source" to its "caller". Off by default; since 1.4.
  • showThread — the name of the thread that logged, in square brackets after the date: [main], [pool-1-thread-3]. Off by default; with a thread pool it tells the interleaved lines of different tasks apart. JsonLogger always writes the thread.
  • showContext — the pairs of LOG.context(...) after the message, requestId=r-17. On by default; since 1.4. See Context.
  • stream — which levels go to System.err: err@ERROR (the default) sends only errors there, err@WARN warnings and errors, err everything, out nothing. A single stream keeps errors in a pipe and the lines in order when standard output and standard error are captured separately.
  • multiline — what an entry does with line breaks and control characters: keep (the default) writes them as they are; indent starts every line of an entry after the first with a tab, like stack frames, so a line without a tab begins an entry and a message cannot forge one; escape writes them as \r and \n, so an entry and its stack trace are one physical line for grep and tail. Both modes write other control characters, the escape sequences of a terminal among them, as \u001b, and keep the tab. They also escape the bidi controls, U+202A to U+202E and U+2066 to U+2069, which reorder what follows in a terminal, and the tags, U+E0000 to U+E007F, which spell text that a terminal does not show and a language model still reads, as \u202e; the joiners of emoji and Persian and the other format characters stay. JsonLogger escapes its lines anyway. Since 1.4.
  • color — when the level word is coloured: red ERROR, yellow WARN, green INFO, dim DEBUG and TRACE, magenta DBG. auto (the default) colours only a terminal and follows the NO_COLOR and FORCE_COLOR conventions: no colours when NO_COLOR is set, colours when FORCE_COLOR is set to anything but 0 or false, otherwise only when standard output is a terminal and TERM is not dumb. A pipe, a file, the run log and JsonLogger never get escape codes. On Windows auto does not colour without FORCE_COLOR: the console shows the codes as text unless the program turns their processing on, which Java does not do. always and never ignore the environment; agent mode uses never. Since 1.4.
  • repeats — what happens to consecutive repeats of an entry, the same level, source, call site, message, fields, context and exception: keep (the default) writes each; collapse writes the first in full; when another entry comes, the logger is replaced or the run ends, it writes one line with the count, without the stack trace: WARN [Poller] Connection refused: db:5432 (repeated 41 more times in 20.3 s). A series that goes on writes its count every ten seconds, so tail -f still shows it. Only the console collapses: the run log, JsonLogger and MemoryLogger get every entry, and the run summary counts them all. Agent mode uses collapse; since 1.4.
  • exceptionExclude / exceptionMaxFrames — shorter stack traces, see Shorter stack traces.
  • traceEnabled … errorEnabled — per-level switches; everything is enabled by default, so switch TRACE and DEBUG off in production, in code or with nanolog.level=INFO. Disabled levels are rejected before the LogEntry is built, so lazy messages are never evaluated. setLevel(level) sets all five at once, and the switches may change while other threads log; see Changing levels at run time.

For a custom layout (other colours, a different order) extend ConsoleLogger and
override getOutputStream, writeLevel, writeDate, writeSource, writeTags, writeMessage,
writeFields, writeContext, writeSourceLine, writeThrowable or addDelimiter.

Levels and options without code

The constructor of ConsoleLogger reads these settings from system properties, environment variables and nanolog.properties, in this order of precedence:

Property Environment variable Meaning
nanolog.level NANOLOG_LEVEL the lowest enabled level: TRACE (default), DEBUG, INFO, WARN, ERROR, OFF
nanolog.level.<package or class> — the level for one package or class
nanolog.levels NANOLOG_LEVELS several such rules in one value: com.acme.payments=DEBUG,com.acme.db=TRACE
nanolog.console.showLevel NANOLOG_CONSOLE_SHOWLEVEL true or false, like the setter
nanolog.console.showDate NANOLOG_CONSOLE_SHOWDATE the same
nanolog.console.showSource NANOLOG_CONSOLE_SHOWSOURCE the same
nanolog.console.showSourceFullName NANOLOG_CONSOLE_SHOWSOURCEFULLNAME the same
nanolog.console.sourceLength NANOLOG_CONSOLE_SOURCELENGTH a number of characters, 0 (default) for the full name, like the setter
nanolog.console.showLocation NANOLOG_CONSOLE_SHOWLOCATION the same
nanolog.console.showThread NANOLOG_CONSOLE_SHOWTHREAD the same
nanolog.console.showSourceLine NANOLOG_CONSOLE_SHOWSOURCELINE the same
nanolog.console.showContext NANOLOG_CONSOLE_SHOWCONTEXT the same
nanolog.console.stream NANOLOG_CONSOLE_STREAM out, err or err@LEVEL (default err@ERROR), like the setter
nanolog.console.multiline NANOLOG_CONSOLE_MULTILINE keep (default), indent or escape, like the setter
nanolog.console.repeats NANOLOG_CONSOLE_REPEATS keep (default) or collapse, like the setter
nanolog.console.color NANOLOG_CONSOLE_COLOR auto (default), always or never, like the setter
nanolog.console.dateFormat NANOLOG_CONSOLE_DATEFORMAT a SimpleDateFormat pattern, or iso for yyyy-MM-dd'T'HH:mm:ss.SSSXXX, 2026-11-18T10:30:00.000+01:00
nanolog.console.timeZone NANOLOG_CONSOLE_TIMEZONE a time zone ID such as UTC, Europe/Berlin or GMT+03:00, like the setter; an ID that Java does not know is reported instead of being taken for GMT
nanolog.exception.exclude NANOLOG_EXCEPTION_EXCLUDE package or class prefixes whose stack frames are collapsed, comma-separated
nanolog.exception.maxFrames NANOLOG_EXCEPTION_MAXFRAMES the most stack frames per throwable; 0 (default) for no limit
nanolog.file NANOLOG_FILE the file of FileLogger, nanolog.log by default
nanolog.file.append NANOLOG_FILE_APPEND true (default) or false, which empties the file when it opens
nanolog.file.maxSize NANOLOG_FILE_MAXSIZE the size at which the file rolls over, such as 10MB; 0 (default) for none
nanolog.file.backups NANOLOG_FILE_BACKUPS how many rolled-over files are kept, 3 by default
nanolog.file.flush NANOLOG_FILE_FLUSH entry (default, each entry at once) or buffer
nanolog.file.format NANOLOG_FILE_FORMAT text (default) or json
java -Dnanolog.level=WARN -Dnanolog.level.com.acme.payments=DEBUG -jar app.jar
NANOLOG_LEVEL=WARN NANOLOG_LEVELS=com.acme.payments=DEBUG java -jar app.jar
  • A package or class rule beats the global level, however that level was set, setters included. Turning DEBUG on for one package therefore needs no code change.
  • The most specific rule wins: the class itself, then its enclosing classes, then its packages from the innermost outwards. A rule matches whole name segments only, so com.acme.pay does not cover com.acme.payments.
  • nanolog.level.<name> beats an item for the same name in nanolog.levels.
  • Setters called after the constructor override the values it read, so new ConsoleLogger().setDebugEnabled(false) in code wins over nanolog.level; package and class rules still apply on top.
  • [NANOLOG] lines are notices of what Nanolog does and diagnostics of its own problems. A diagnostic says where it comes from: a setting and where it was set (set as a system property, set by the environment variable NANOLOG_LEVEL, set in file:/.../nanolog.properties), a logger class or a call site. Each distinct diagnostic is printed once per JVM; nanolog.diagnostics=all prints every one, including each failure of a logger, and off none, while ILogger.onDiagnostic still gets the findings of strict mode and of nanolog.dbg=fail. The run summary, the line of agent mode and the path of the run log are notices with switches of their own.
  • An invalid value prints a [NANOLOG] diagnostic to System.err and is ignored; logging goes on. A diagnostic is always one line: control characters in the value it repeats are printed as escapes such as \u000a, and so are format characters, such as the bidi override \u202e, which would make the line read in another order.
  • nanolog.properties is read when LOG initialises, so a ConsoleLogger created before that sees only -D and the environment.

Changing levels at run time

The levels of ConsoleLogger and JsonLogger can change while the application runs, for a verbose mode, an admin endpoint or a test:

LOG.setLevel(LogEntryLevel.INFO);                         // the global level
LOG.setLevel("com.acme.payments", LogEntryLevel.DEBUG);   // one package or class, like nanolog.level.<name>
LOG.setLevel("com.acme.noisy", "OFF");                    // a string, as in the settings: OFF works too
LOG.clearLevel("com.acme.payments");                      // the global level applies to it again
LOG.resetLevels();                                        // back to -D, the environment and nanolog.properties

try (LOG.LevelOverride ignored = LOG.withLevel("com.acme", LogEntryLevel.TRACE)) {
    // TRACE for com.acme until the block ends
}
  • A change takes effect on the next logging call in every thread, threads that are already running included.
  • A level set for a package or class works exactly like nanolog.level.<name>: it beats the global level, and the most specific rule wins. LOG.setLevel(level) changes only the global level and leaves such rules alone.
  • LOG.withLevel(...) restores the rule the name had when the try block ends, even when it ends with an exception. The change is JVM-wide. Nested overrides of the same name restore correctly when they close in reverse order, as try-with-resources does.
  • LOG.resetLevels() reads nanolog.level, nanolog.levels and nanolog.level.<name> again: from -D and the environment as they are now, from nanolog.properties as it was loaded at startup. It undoes every change made at run time, the level setters of ConsoleLogger included; the display options stay as they are.
  • CompositeLogger passes each change to those of its delegates that support it. The other loggers have no levels to change: Slf4jLogger takes them from the SLF4J backend, and MemoryLogger captures everything. When such a logger is installed directly, the first call prints one [NANOLOG] line and nothing changes.
  • A level may also be given as a string, as in the settings: TRACE to OFF, ignoring case. LOG.setLevel("com.acme.noisy", "OFF") switches a package off, and a value from a request or a command line needs no parsing of your own.
  • A null or blank name and a null or unknown level print a [NANOLOG] diagnostic and change nothing.
  • The same methods exist on ConsoleLogger, and so on JsonLogger and FileLogger, and on CompositeLogger. A custom logger supports LOG.setLevel(...) by implementing ILevelControl.

Shorter stack traces

Most frames of a stack trace carry no signal: test runners, reflection, proxies. Two settings shorten the traces that ConsoleLogger and JsonLogger print:

-Dnanolog.exception.exclude=org.junit,sun.reflect,jdk.internal.reflect,java.lang.reflect -Dnanolog.exception.maxFrames=40
java.lang.IllegalStateException: connection refused
	at com.acme.OrderService.load(OrderService.java:87)
	at com.acme.OrderServiceTest.loads(OrderServiceTest.java:21)
	... 68 frames excluded
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
	... 23 frames excluded
  • exclude lists package or class prefixes. A run of two or more consecutive frames that match becomes one ... N frames excluded line; a single matching frame stays, and so does the first frame of every throwable. A prefix matches whole name segments, like a level rule: org.junit covers org.junit.runners.ParentRunner, not org.junitx.
  • maxFrames prints at most that many frames of each throwable, its causes and suppressed exceptions counted separately; the rest becomes ... N more, as the frames shared with the enclosing trace already do.
  • The layout stays that of printStackTrace: Caused by:, Suppressed: with its indentation, circular references marked. Without either setting the text is exactly what printStackTrace prints. A trace that cannot be shortened, because the throwable breaks while it is read, is printed the usual way.
  • In code: setExceptionExclude("org.junit", ...) and setExceptionMaxFrames(40) on ConsoleLogger and JsonLogger. Slf4jLogger is not affected: its backend prints exceptions itself.

JsonLogger

One JSON object per line, for jq, log collectors and scripts. It needs no JSON library and is selected without code:

-Dnanolog.logger=com.nanolaba.logging.JsonLogger
{"ts":"2026-11-11T02:30:31.412Z","level":"WARN","logger":"com.acme.PaymentService","thread":"main","message":"Charge of 42 failed, retrying","template":"Charge of {} failed, retrying","args":["42"],"fields":{"amount":42},"context":{"requestId":"r-17"},"caller":{"class":"com.acme.PaymentService","method":"charge","file":"PaymentService.java","line":87}}
  • ts — ISO-8601 in UTC with milliseconds, sortable as text; level, logger (the source class), thread, tags (the tag of LOG.tag(...), when there is one), message (the formatted message).
  • template and args — the raw message and the arguments as strings, for parameterized messages only; equal events can be grouped whatever their arguments.
  • dbg, breadcrumb — true for an entry of LOG.dbg and for one held back by nanolog.buffer, see Breadcrumbs.
  • fields — the arguments of LOG.kv(...) as a nested object, when there are any; args leaves out those that no {} takes. Select on them with jq 'select(.fields.orderId=="A-17")'; see Fields.
  • context — the pairs of LOG.context(...) as a nested object, when there are any. Numbers and booleans keep their JSON type, so jq compares them as numbers: jq 'select(.context.attempt > 1)'.
  • caller — the call site, when the source class was detected, with its source line under showSourceLine; exception — class, message and stackTrace, when there is a throwable. Fields without a value are left out.
  • Line breaks and control characters are escaped, so one entry is always exactly one line, stack trace included.
  • JsonLogger extends ConsoleLogger: the same levels, the same level properties and the same streams (ERROR to System.err by default). The display options do not apply.
  • In a pipe only standard output reaches the next program, so java -jar app.jar | jq would lose every ERROR entry. -Dnanolog.console.stream=out writes them to standard output with the rest, in the order they were logged.

FileLogger

Since 1.4.

Writes the entries to a file, for an application with no console to redirect (a desktop or an Android app) or a service that keeps a log of its own:

nanolog.logger=com.nanolaba.logging.FileLogger
nanolog.file=logs/app.log
nanolog.file.maxSize=10MB
nanolog.file.backups=3
  • The file is appended to, and its directory created, when the first entry comes; nanolog.file.append=false empties it then. Without nanolog.file it is nanolog.log in the working directory.
  • Each entry is written through at once, so a crash loses nothing that was logged. nanolog.file.flush=buffer keeps entries in memory until LOG.flush(), a full buffer of 8 KB or the exit of the JVM, for a program that logs a lot.
  • nanolog.file.maxSize rolls the file over: app.log becomes app.log.1, the older files move one up, and the oldest beyond nanolog.file.backups is deleted. There is no rolling by date, no compression and no asynchronous writing.
  • The lines have the layout of ConsoleLogger and follow its settings, levels included; nanolog.file.format=json writes the lines of JsonLogger instead. Repeats are not collapsed, there are no colours, and agent mode leaves the file as it is.
  • A file that cannot be written is reported once with a [NANOLOG] line, and its entries go to System.err; a rollover that fails is reported too, and the file keeps growing. Nothing is thrown.
  • The console and a file together, in code: LOG.init(new CompositeLogger(new ConsoleLogger(), new FileLogger(Paths.get("logs/app.log")))). The setters setAppend, setMaxSize, setBackups, setFlush and setFormat change the settings, and close() closes the file until the next entry.

Slf4jLogger

The bridge to SLF4J. Each entry is forwarded to the org.slf4j.Logger named after the source class, so your SLF4J backend sees the real caller, not LOG. Levels, patterns, appenders and files are configured in that backend as usual. SLF4J 1.7 and 2.x both work: CI runs the tests against both.

[!NOTE]
slf4j-api is a provided dependency of Nanolog. Add it and a backend to your project yourself.

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>2.0.20</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.5.38</version>
</dependency>
LOG.init(new Slf4jLogger());

Things to know:

  • Location-aware backends, Logback and Log4j 2 among them, are told that the call site is the first frame after LOG. Their own %file:%line, %method and %class (Logback) or %l (Log4j 2) therefore show the code that called LOG, not Slf4jLogger, with no backend configuration. slf4j-simple prints no location at all.
  • A timer or a unit of work writes its line when it ends, and the backend reads the call site from the stack at that moment. LOG.timed(...), LOG.unit(name, body) and run(...) therefore show their own call. A timer or a unit closed by a try-with-resources block shows the line where the block ends, in the same method: the LOG.time or LOG.unit call is no longer on the stack, and SLF4J has no way to pass a call site. A unit written as interrupted at the end of the run shows a frame of Nanolog. ConsoleLogger, JsonLogger and the run log show the LOG.time or LOG.unit call in every case.
  • In agent mode LOG.dbg prints whatever the levels: a LOG.dbg line whose class has DEBUG off in the backend, the root at INFO as in Spring Boot, is printed by Nanolog on System.out in the format of its agent console, instead of being passed to a backend that would drop it. With DEBUG on, the backend prints it with its own pattern and call site.
  • The message reaches SLF4J already formatted, so the backend does not see the {} arguments as structured data. Fields of LOG.kv(...) that no {} takes are appended to the text as key=value, as ConsoleLogger writes them; the key-value pairs of SLF4J 2 are not used, since backends treat them differently. The tag of LOG.tag(...) is passed as an SLF4J Marker of that name, so %marker of Logback prints it and the filters of the backend can select on it.
  • The pairs of LOG.context(...) are put into the MDC while an entry is forwarded and taken out afterwards; values the MDC already held for those keys are put back. Backends that support MDC (Logback and Log4j 2) print them through their own patterns such as %X{requestId}, like values set through org.slf4j.MDC; slf4j-simple and slf4j-nop silently discard them, and the JUL binding (slf4j-jdk14) stores them without printing.
  • An entry without a message is passed with an empty message, not the word null.
  • An entry without a source class goes to the SLF4J ROOT logger.
  • Loggers are cached per source class in a ConcurrentHashMap and never evicted, so with dynamic class reloading the cache retains Class references.

JulLogger

Since 1.4.

Writes the entries to java.util.logging, for an application that configures its logging there, with no SLF4J and no binding:

nanolog.logger=com.nanolaba.logging.JulLogger
  • Each entry goes to the JUL logger named after its source class. JUL decides the levels (logging.properties), and LOG.isDebugEnabled() asks it. TRACE, DEBUG, INFO, WARN and ERROR become FINEST, FINE, INFO, WARNING and SEVERE, so LOG.dbg is a FINE record. In agent mode a LOG.dbg line that JUL would drop is printed by Nanolog on System.out instead, as with Slf4jLogger.
  • The message arrives formatted, followed by the fields of LOG.kv and the context as key=value, since JUL has no place for them; the record names the call site as its source class and method, which %2$s of SimpleFormatter prints.
  • On the module path the application needs the module java.logging.

MemoryLogger and CompositeLogger

MemoryLogger keeps entries in memory for tests. Every level is enabled, so entries are captured whatever the production configuration says, and nothing is printed.

void chargeIsRetried() {
    try (MemoryLogger log = MemoryLogger.install()) { // close() puts the previous logger back
        new PaymentService().charge(42); // the code under test

        log.assertLogged(LogEntry.LogEntryLevel.WARN, "Charge of 42 failed, retrying");
        log.assertNoneAtOrAbove(LogEntry.LogEntryLevel.ERROR); // a failure lists everything that was logged
    }
}
  • install() replaces the logger of LOG and remembers the previous one; close() puts it back, even when the test fails. installForwarding() does the same but still passes every entry to the previous logger, so the usual output stays visible.
  • getEntries(), getEntries(level), getEntries(SomeClass.class), getMessages(), contains(level, text), clear() — snapshots and short assertions; the logger is thread-safe.
  • assertNoneAtOrAbove(WARN), assertLogged(level, text), assertTemplateLogged(level, "Retry {} of {}") — assertions that throw AssertionError without JUnit or AssertJ. The message lists every captured entry with its call site and stack trace, so the failing test shows what was logged without a second run. assertNoneAtOrAbove(WARN) checks that the code logged no warning and no error; assertTemplateLogged matches the message before its arguments were substituted.
  • new MemoryLogger(capacity) keeps only the newest entries.
  • LOG.init and install() are JVM-wide, so tests that install a logger must not run in parallel with each other. For parallel tests use capture(), below.

Since 1.4, capture() keeps the entries of the current thread only, so tests that JUnit runs in parallel in one JVM each see their own, while the logger of LOG stays installed for the others:

void chargeIsRetriedInParallel() { // safe while JUnit runs other tests in parallel
    try (MemoryLogger log = MemoryLogger.capture()) { // this thread only; the logger of LOG stays installed
        new PaymentService().charge(42);

        log.assertLogged(LogEntry.LogEntryLevel.WARN, "Charge of 42 failed, retrying");
    }
}
  • The capture takes every level, whatever the levels of the logger. The entries of this thread do not reach that logger, the run log or the run summary, though a logger installed while the capture is open, MemoryLogger.install() for one, receives them; captureForwarding() passes them on as well, at the levels the logger has enabled. The findings of strict mode and of nanolog.dbg=fail on this thread go to the capture too, for assertNoDiagnostics().
  • Only the current thread is captured: entries that the code under test logs from a thread pool reach the logger of LOG. Captures nest, and close() may run on any thread.
  • Without an open capture logging reads one counter and nothing else of the captures.

CompositeLogger sends every entry to several loggers. Each of them receives only the levels it has enabled, and a lazy message is built only if at least one of them wants it. A logger that throws is reported once with a [NANOLOG] line and skipped; the others still receive the entry:

MemoryLogger memory = new MemoryLogger(1000); // keeps the newest 1000 entries
LOG.init(new CompositeLogger(memory, new ConsoleLogger()));

Logs in tests: only the failing ones

Since 1.4.

The log of a passing test is noise; the log of a failing one is the evidence. A Spring Boot test suite can print thousands of lines per green run, and the agent, or the person, reading it cannot find the failure in them. NanologExtension holds back what each test writes and prints it only when the test fails.

@ExtendWith(NanologExtension.class)
class PaymentServiceTest {

    @Test
    void chargeIsRetried() { ... }
}
--- log of PaymentServiceTest.chargeIsRetried ---
INFO 17.11.2026 10:15:02 [PaymentService] Charging order 17
WARN 17.11.2026 10:15:02 [PaymentService] Charge of 42 failed, retrying
--- end of the log of PaymentServiceTest.chargeIsRetried ---
  • What is held back. What the thread of the test writes to the logger of LOG, at the levels of that logger, from the @BeforeEach methods to the @AfterEach ones. When the test fails, it is written to that logger after all, between the two lines above; when it passes or is aborted, it goes only to the run log, if that is on. A failed test that logged nothing prints nothing.
  • The log of the class. What the class logs outside its tests is held back too: its @BeforeAll and @AfterAll methods, and the creation of each test instance, where SpringExtension starts the application context and the beans log their start-up. When a test of the class fails, or the class itself does, as when a @BeforeAll method throws, it is printed after the tests of the class, between --- log of class PaymentServiceTest --- and --- end of the log of class PaymentServiceTest ---; otherwise it goes only to the run log. Spring caches the context, so the class that happens to start it holds its log. With @TestInstance(Lifecycle.PER_CLASS) JUnit creates the instance before the extension starts, so what is logged then is printed as usual. Since 1.4.1.
  • Parallel tests. Each test holds back the entries of its own thread, so tests that JUnit runs in parallel keep their logs apart. Entries that the code under test logs from a thread pool are not held back.
  • MemoryLogger works as usual. A test that installs a MemoryLogger or opens MemoryLogger.capture() sees its entries; see MemoryLogger and CompositeLogger.
  • Settings. nanolog.junit.output (NANOLOG_JUNIT_OUTPUT): failed, the default, all (every log, as it is written) or none. With junit.jupiter.extensions.autodetection.enabled=true in junit-platform.properties JUnit registers the extension for every test class, without @ExtendWith.
  • No dependency. The extension is compiled against the JUnit Jupiter API, which the tests have anyway; Nanolog itself still has none.

Message formatting

LOG.info("User {} logged in from {}", "alice", "10.0.0.1");  // User alice logged in from 10.0.0.1
LOG.info("Missing arguments stay as is: {} {}", 1);          // Missing arguments stay as is: 1 {}
LOG.info("Extra arguments are ignored: {}", 1, 2);           // Extra arguments are ignored: 1
LOG.info("Escaped placeholder: \\{} then {}", 1);           // Escaped placeholder: {} then 1
LOG.info("Escaped backslash: \\\\{}", 1);                  // Escaped backslash: \1
LOG.info("Arrays: {} and {}", new int[]{1, 2}, new String[][]{{"a"}, {"b"}}); // Arrays: [1, 2] and [[a], [b]]
LOG.info("Null is fine: {}", (Object) null);                 // Null is fine: null
LOG.info("Broken toString(): {}", new BrokenToString());     // Broken toString(): [FAILED toString()]
LOG.error("Failed to load {}", "order", new IOException("timeout")); // Failed to load order, then the stack trace
LOG.error("Cause: {}", new IOException("timeout"));          // Cause: java.io.IOException: timeout
  • {} is replaced by the next argument; \{} is a literal {} and consumes no argument; \\{} is a literal backslash followed by a substitution.
  • A Throwable in the last position that no {} consumes is not an argument: it becomes the exception of the entry, and its stack trace is logged, as in SLF4J. In LOG.error("Cause: {}", e) the placeholder takes the exception, so only e.toString() is printed. An exception passed first always wins; a trailing one then stays an ordinary argument.
  • Primitive arrays are rendered with Arrays.toString, object arrays with Arrays.deepToString.
  • Every toString() is guarded: if it throws, the value becomes [FAILED toString()] and nothing propagates to the caller. A throwable whose stack trace cannot be printed becomes [FAILED printStackTrace()].
  • A lazy message is guarded the same way: if its Supplier throws, the entry is still logged, with the message [FAILED supplier: <exception>], for example [FAILED supplier: java.lang.IllegalStateException: no report]; the exception and the arguments of the entry are kept. The supplier runs at most once.
  • LOG.lazy(supplier) makes one argument lazy: LOG.debug("Stats: {}", LOG.lazy(() -> summarize(stats))) computes the value only if the level is enabled and only once, however many loggers format the entry. Unlike a lazy message, the template stays a template for strict mode, for the template and args of JsonLogger and for assertTemplateLogged, and no isDebugEnabled() check is needed. A supplier that throws gives [FAILED supplier: <exception>] in place of the value. There are no overloads that take a Supplier for the arguments: they would make calls ambiguous, from Kotlin as well.
  • The message object itself may be anything, not only a String; it is converted with the same guarded toString().
  • With nanolog.dump=auto (NANOLOG_DUMP=auto) an argument whose class has no toString() of its own is printed field by field, as in LOG.dbg: LOG.info("Added {}", line) prints Added Line{sku="A-1", qty=2} instead of Added Line@1e643faf. Collections, maps, arrays and Optional are walked, so a list of such objects is printed the same way. Everything with a toString() of its own, strings included, prints as before, without quotes, limits or redaction. The setting is off by default because it changes existing output; JsonLogger puts the result into message and args as text. Since 1.4.

Fields: named arguments

Since 1.4.

LOG.kv(key, value) names an argument, so that a script or an agent can select the entry by it instead of matching the text of the message:

LOG.info("Loaded {} items from {}", LOG.kv("count", count), LOG.kv("source", source));
// INFO 16.11.2026 10:15:02 [Importer] Loaded 3 items from db
// JSON: "message":"Loaded 3 items from db",...,"fields":{"count":3,"source":"db"}

LOG.info("Payment accepted", LOG.kv("orderId", orderId));
// INFO 16.11.2026 10:15:02 [PaymentService] Payment accepted orderId=A-17
// JSON: "message":"Payment accepted","fields":{"orderId":"A-17"}

LOG.error("Payment failed", LOG.kv("orderId", orderId), e); // the exception goes last
  • In a {} a field prints its value like any argument, so existing messages keep their text.
  • A field that no {} takes is not an extra argument: ConsoleLogger and Slf4jLogger append it as key=value, quoted like the pairs of the context, and strict mode does not report it.
  • JsonLogger writes every field into "fields", whether a {} took it or not; numbers and booleans stay JSON numbers and booleans. Any logger reads them from LogEntry.getFields(), and those the message does not show from getTrailingFields().
  • An exception goes last, after the fields, and becomes the exception of the entry as usual. A key given twice keeps its last value; LOG.kv(null, value) is a plain argument.
  • Names inside the braces, {orderId}, are not supported: {word} is ordinary text in existing messages.

Checking placeholders in tests

Leniency about {} is right in production, but during development it hides mistakes: a dropped argument
leaves no trace in the output at all. With nanolog.strict=true (or NANOLOG_STRICT=true), every call
with arguments whose number of {} placeholders differs from the number of arguments additionally
prints one line with the call site to System.err:

[NANOLOG] com.acme.PaymentService.charge(PaymentService.java:87): 2 placeholders, 1 argument in "Charge of {} for {}"

Two more mistakes are reported the same way, with the call site:

[NANOLOG] com.acme.PaymentService.charge(PaymentService.java:91): argument 1 repeats the message of the exception
[NANOLOG] com.acme.LoginService.login(LoginService.java:40): the template is not a constant: "User 17 logged in from {}"
  • An argument that is the message of the exception logged with it, as in LOG.error("Charge failed: {}", e.getMessage(), e): the stack trace prints the message already. Name what failed instead: LOG.error("Charge of {} failed", orderId, e). Only the string that getMessage() returns counts, and an exception without a message is not checked.
  • A call site seen with two templates, as in LOG.info("User " + id + " logged in from {}", ip): a template built from data groups nothing, since the template of JsonLogger and assertTemplateLogged see a new one every time. Put the value into a {}: LOG.info("User {} logged in from {}", id, ip). The first template of each call site is remembered. Calls without arguments, such as LOG.info(report), and calls with an explicit class are not checked. A call site is a line, so two calls on one line count as one, and a template chosen by ?: between two constants is reported too.

For all three checks:

  • The entry itself is logged exactly as without the check, and nothing is thrown.
  • Each finding is printed once; the 1000 most recent printed findings are remembered.
  • Only calls with arguments and enabled levels are checked. Escaped \{} does not count, and a trailing exception taken as the exception of the entry is not an argument.
  • When the check is off, it costs one boolean test per call. The setting is read by LOG.init().

Turn it on for test runs, so mismatches show up in the output that is read anyway:

<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <systemPropertyVariables>
            <nanolog.strict>true</nanolog.strict>
        </systemPropertyVariables>
    </configuration>
</plugin>
test {
    systemProperty 'nanolog.strict', 'true'
}

A line on standard error is easy to miss among thousands; MemoryLogger turns it into a failing test. Strict mode hands every finding to the installed logger as well (ILogger.onDiagnostic), every occurrence and not only the first one of a template, so a test fails even when an earlier test met the same mismatch:

void noPlaceholderMismatches() { // the test run sets -Dnanolog.strict=true
    try (MemoryLogger log = MemoryLogger.install()) {
        new PaymentService().charge(42);

        log.assertNoDiagnostics(); // fails with the call site and the template of every mismatch
    }
}
  • getDiagnostics() returns the findings, assertNoDiagnostics() fails with all of them in the message; clear() drops them together with the entries. CompositeLogger passes them to its delegates.
  • Without strict mode there is nothing to report and assertNoDiagnostics() passes, so switch it on for the test run as above.
  • nanolog.dbg=fail reports LOG.dbg calls the same way, see Leftover calls.

Logging payloads safely

Since 1.4.

Prompts and responses of a language model, request bodies and documents are either not logged at all or logged raw, keys pasted into them included. LOG.content(value) is the middle ground: the text in development, a summary in production.

LOG.debug("Prompt to {}: {}", model, LOG.content(prompt));
// by default:                     Prompt to gpt-x: [content 1834 chars #3f2a9c1b]
// -Dnanolog.content=truncate:20:  Prompt to gpt-x: You are a helpful as... [+1814 chars]
// -Dnanolog.content=show:         Prompt to gpt-x: You are a helpful assistant.\nAnswer briefly. ...

LOG.info("Answer received", LOG.kv("answer", LOG.content(answer)), LOG.kv("tokens", 812));
// JSON: "fields":{"answer":{"content_len":5120,"content_hash":"9c41d2e7"},"tokens":812}
  • By default a payload is its length and a hash of eight hexadecimal digits. Equal payloads have equal hashes within a run, so a repeated prompt or a retry is recognised without its text; the hash is keyed with a random key of the JVM, so the log does not reveal a short payload, such as a pasted key, to someone who tries candidates. Java AI frameworks keep prompt content out of the logs by default for the same reason, and the logs a coding agent reads are sent to its model provider.
  • nanolog.content (NANOLOG_CONTENT) is hide, truncate:<characters> or show, and nanolog.content.<package or class> sets it for one package or class, the most specific rule winning, as with levels: -Dnanolog.content.com.acme.llm=show shows the prompts of one package while you debug. Rules for packages are system properties or keys of nanolog.properties.
  • Escaped. In the text that reaches the log, line breaks and control characters are escaped, \n and \u001b, so a pasted payload cannot forge a log line, and so are the bidi controls and the tags, \u202e, so a model reply cannot hide text in it either; a tab stays.
  • Taken once. The text is taken when the entry is created, with the guarded toString() of a {} argument, so a payload that changes later or breaks its toString() changes nothing. A payload in a LOG.context(...) is taken for each entry and follows the rule of the class of that entry.
  • JSON. In "fields" and "context" a hidden payload is {"content_len":1834,"content_hash":"3f2a9c1b"}; message and args hold the text as the console writes it.
  • Known keys are masked. A shown or truncated payload has keys of model providers (sk-...), AWS access keys (AKIA...), bearer tokens and JSON web tokens replaced by sk-***, AKIA***, Bearer *** and eyJ***. Other secrets inside it, such as a password in plain words, are written as they are; only payloads are scanned, never the text of messages.

Masking secrets

Since 1.4.

Tokens and passwords reach the log through {} arguments, fields and the context, and the logs a coding agent reads are sent to its model provider. LOG.secret(value) marks a secret, and fields and context named like secrets are masked without it:

LOG.info("Login of {} with {}", user, LOG.secret(token));
// INFO 16.11.2026 10:15:02 [AuthService] Login of alice with ***

LOG.info("Connected", LOG.kv("url", url), LOG.kv("password", password));
// INFO 16.11.2026 10:15:02 [Database] Connected url=jdbc:postgresql://db/shop password=***
  • LOG.secret keeps no value and never formats it, so its toString() is not called; every logger writes ***, in the message, in args and fields of JsonLogger, in the MDC of Slf4jLogger and in the assertion messages of MemoryLogger.
  • A field of LOG.kv(...) or a value of LOG.context(...) is masked when its key, or a word of it, is in nanolog.redact (NANOLOG_REDACT): by default password, passwd, secret, token, apikey, credential and authorization. Words are split at separators and at camel case, so password covers db.password and userPassword, and token covers X-Auth-Token but not input_tokens. The value is masked when the entry is created, so a {} that takes the field shows *** too. A list replaces the default one; an empty value turns masking off.
  • The text of messages is not scanned: scanning every message is slow and gives a false sense of safety. Payloads of LOG.content have the known key formats masked when they are shown.

Logging LLM calls

Since 1.4.

Spring AI and LangChain4j have switches that log requests and responses, but they print toString() dumps and pretty-printed JSON. A listener or an advisor of about twenty lines logs one line per call through Nanolog instead: the model, the tokens, the latency and the finish reason, under the field names of the OpenTelemetry GenAI semantic conventions (the gen_ai.client.inference span, status Development in November 2026). The prompt and the completion go through LOG.content, and at DEBUG so does a short transcript.

[!NOTE]
These snippets are not compiled by the build of Nanolog, which targets Java 8, while both frameworks need Java 17. They are written against LangChain4j 1.x and Spring AI 2.0.

LangChain4j

A ChatModelListener, registered with .listeners(List.of(new NanologChatListener())) on the builder of the model:

public class NanologChatListener implements ChatModelListener {

    @Override
    public void onRequest(ChatModelRequestContext context) {
        context.attributes().put("nanolog.start", System.nanoTime());
        if (LOG.isDebugEnabled()) {
            LOG.debug("chat request {}", LOG.content(transcript(context.chatRequest().messages())));
        }
    }

    @Override
    public void onResponse(ChatModelResponseContext context) {
        ChatResponseMetadata metadata = context.chatResponse().metadata();
        TokenUsage usage = metadata.tokenUsage();
        long start = (Long) context.attributes().get("nanolog.start");
        LOG.info("chat {} {} ms",
                 LOG.kv("gen_ai.request.model", context.chatRequest().parameters().modelName()),
                 LOG.kv("duration_ms", (System.nanoTime() - start) / 1_000_000),
                 LOG.kv("gen_ai.provider.name", context.modelProvider()),
                 LOG.kv("gen_ai.response.model", metadata.modelName()),
                 LOG.kv("gen_ai.usage.input_tokens", usage == null ? null : usage.inputTokenCount()),
                 LOG.kv("gen_ai.usage.output_tokens", usage == null ? null : usage.outputTokenCount()),
                 LOG.kv("gen_ai.response.finish_reasons", metadata.finishReason()),
                 LOG.kv("gen_ai.output.messages", LOG.content(context.chatResponse().aiMessage().text())));
    }

    @Override
    public void onError(ChatModelErrorContext context) {
        LOG.error(context.error(), "chat {} failed",
                  LOG.kv("gen_ai.request.model", context.chatRequest().parameters().modelName()));
    }

    private static String transcript(List<ChatMessage> messages) {
        StringBuilder out = new StringBuilder();
        for (ChatMessage message : messages) {
            String text = message instanceof SystemMessage s ? s.text()
                        : message instanceof UserMessage u && u.hasSingleText() ? u.singleText()
                        : message instanceof AiMessage a ? a.text()
                        : message instanceof ToolExecutionResultMessage t ? t.text()
                        : String.valueOf(message);
            out.append('[').append(message.type()).append("] ").append(text).append('\n');
        }
        return out.toString();
    }
}
INFO [NanologChatListener] chat gpt-4o-mini 812 ms gen_ai.provider.name=OPEN_AI gen_ai.response.model=gpt-4o-mini-2024-07-18 gen_ai.usage.input_tokens=1834 gen_ai.usage.output_tokens=212 gen_ai.response.finish_reasons=STOP gen_ai.output.messages="[content 980 chars #9c41d2e7]"

Spring AI

A CallAdvisor, registered with ChatClient.builder(chatModel).defaultAdvisors(new NanologAdvisor()). It makes each call a unit of work, so the line gets the outcome and the latency, and a thrown exception is attached to it:

public class NanologAdvisor implements CallAdvisor {

    @Override
    public String getName() {
        return "NanologAdvisor";
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE; // the last advisor, next to the model
    }

    @Override
    public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) {
        Prompt prompt = request.prompt();
        if (LOG.isDebugEnabled()) {
            LOG.debug("chat request {}", LOG.content(transcript(prompt.getInstructions())));
        }
        LOG.Unit unit = LOG.unit("chat")
                           .put("gen_ai.request.model", prompt.getOptions() == null ? null : prompt.getOptions().getModel());
        return unit.run(() -> {
            ChatClientResponse response = chain.nextCall(request);
            ChatResponse chat = response.chatResponse();
            if (chat != null) {
                ChatResponseMetadata metadata = chat.getMetadata();
                Generation result = chat.getResult();
                unit.put("gen_ai.response.model", metadata.getModel())
                    .put("gen_ai.response.id", metadata.getId())
                    .put("gen_ai.usage.input_tokens", metadata.getUsage().getPromptTokens())
                    .put("gen_ai.usage.output_tokens", metadata.getUsage().getCompletionTokens())
                    .put("gen_ai.response.finish_reasons", result == null ? null : result.getMetadata().getFinishReason())
                    .put("gen_ai.output.messages", LOG.content(result == null ? null : result.getOutput().getText()));
            }
            return response;
        });
    }

    private static String transcript(List<Message> messages) {
        StringBuilder out = new StringBuilder();
        for (Message message : messages) {
            out.append('[').append(message.getMessageType()).append("] ").append(message.getText()).append('\n');
        }
        return out.toString();
    }
}
INFO [NanologAdvisor] chat ok 812 ms parent=agent-turn gen_ai.request.model=gpt-4o-mini gen_ai.response.model=gpt-4o-mini-2024-07-18 gen_ai.response.id=chatcmpl-B9x2 gen_ai.usage.input_tokens=1834 gen_ai.usage.output_tokens=212 gen_ai.response.finish_reasons=STOP gen_ai.output.messages="[content 980 chars #9c41d2e7]"
  • A whole agent turn becomes one unit with try (LOG.Unit turn = LOG.unit("agent-turn")) { ... } around it: the calls of the model and the tools inside name it as parent, their warnings and errors count in it, and LOG.wrap carries it into the threads of the tools.
  • Prompts while debugging: -Dnanolog.content=show, or a rule for the package of the listener such as -Dnanolog.content.com.acme.ai=truncate:200. With nanolog.buffer=DEBUG the transcripts are written only before a failure.
  • The field names follow the conventions, the values are what the frameworks report: the provider and the finish reason are enum names such as OPEN_AI and STOP, not the lower-case values of OpenTelemetry. With JsonLogger the fields are typed: jq sums .fields["gen_ai.usage.input_tokens"].

Context: tag the lines of one request

Since 1.4.

LOG.context(key, value) adds a pair to every entry the current thread logs until the scope is closed, so the lines of one request, job or test are found together, with grep requestId=r-17 or by an agent reading the log:

try (LOG.Context c = LOG.context("requestId", requestId)) {
    LOG.info("Charging {}", amount);
    // INFO 16.11.2026 10:15:02 [PaymentService] Charging 42 requestId=r-17

    executor.submit(LOG.wrap(() -> LOG.info("Sending the receipt")));
    // a thread of the pool logs it with requestId=r-17 as well
}
  • ConsoleLogger prints the pairs after the message. A value that is empty or contains a space, a quote or = goes in double quotes, user="John Smith", so every pair reads as one; showContext=false hides them.
  • JsonLogger writes a nested object, "context":{"requestId":"r-17"}, which cannot collide with level, message and the other fields; numbers and booleans keep their JSON type.
  • Slf4jLogger puts the pairs into the MDC while it forwards an entry and takes them out afterwards, so %X{requestId} prints them in Logback and Log4j 2.
  • Every entry keeps its context as LogEntry.getContext(), so MemoryLogger assertions and custom loggers see it, and the assertion messages of MemoryLogger show it.
  • Scopes nest: an inner scope adds a key or sets one again, and closing it puts the previous value back. Close each scope in the thread that opened it, as try-with-resources does.
  • The context belongs to the thread. A pool thread does not inherit it, because it would inherit the context of the code that happened to create the thread. LOG.wrap(task) takes the context and the open unit of LOG.unit(...) when it is called, then runs the task with them in whatever thread and removes them when the task ends, also when it throws.
  • As with ExecutorService.submit, a lambda that returns a value, () -> list.add(item), is a Callable to the compiler; write () -> { list.add(item); } where a Runnable is needed.
  • Every entry reads one ThreadLocal. A thread without a context keeps nothing in it, virtual threads included.

Context providers

The trace ID of OpenTelemetry, of New Relic or of a request scope lives in a context of its own, not in LOG.context. A context provider adds such keys to every entry, without a dependency of Nanolog on that library:

LOG.addContextProvider(() -> {
    SpanContext span = Span.current().getSpanContext();
    if (!span.isValid()) {
        return null;
    }
    Map<String, Object> ids = new LinkedHashMap<>();
    ids.put("traceId", span.getTraceId());
    ids.put("spanId", span.getSpanId());
    return ids;
});
  • A provider is asked when an entry is created, in the thread that logs: only for an enabled level and once per entry, so keep it cheap. It may return null or an empty map; a null key is ignored.
  • Its keys come after the pairs of LOG.context, which win over them, and a provider added earlier wins over a later one. They reach the loggers like the other pairs: ConsoleLogger prints traceId=4bf92f35... after the message, JsonLogger writes them into "context", Slf4jLogger puts them into the MDC for %X{traceId}, and keys named like secrets are masked.
  • A provider that throws is reported once with a [NANOLOG] line, and the entry is logged without its keys. An entry that a provider logs itself gets no keys from the providers.
  • In the configuration, nanolog.context.provider=com.acme.TraceIdProvider names a class that implements Supplier<Map<String, ?>> and has a public no-argument constructor; several are separated by commas and come before the providers of addContextProvider. A class that cannot be created is reported and left out.
  • Providers apply to the whole JVM and stay after LOG.init(); LOG.removeContextProvider(provider) removes one. A task of LOG.wrap(task) asks them in the thread that runs it, where OpenTelemetry has carried its own context.

Rate limiting

A retry loop, a full queue or a deprecated option can print the same line thousands of times, and the line that matters scrolls away. LOG.once() and LOG.atMostEvery(...) limit one statement:

LOG.once().warn("Option {} is deprecated and ignored", key);
LOG.atMostEvery(10, TimeUnit.SECONDS).warn("Queue is full, dropping {}", item);
// the next line that gets through says how many were skipped:
// WARN 16.11.2026 10:15:02 [Worker] Queue is full, dropping 17 [skipped 241]
  • A statement is its call site, the file and line of the call. Two calls on one line share one limit, and so do all the callers of a helper method that logs for them, unless the helper is skipped: Logging helpers.
  • The next entry that gets through carries the number of calls skipped since the previous one: ConsoleLogger prints [skipped 241] after the message, JsonLogger writes "skipped":241, Slf4jLogger appends [skipped 241] to the message, and any logger reads LogEntry.getSkippedCount().
  • The level is checked first, the limit last: a call at a disabled level is not counted, and a skipped call builds no message and formats nothing.
  • once() and atMostEvery(...) offer four shapes at every level: ("... {} ...", args), (() -> message) and both with an exception first. The state of each call site takes a few bytes and is updated without locks, and the number of call sites is bounded by the code.
  • A count left at the end of a burst is printed only when the statement runs again. A period of zero or less limits nothing.

Tags

Since 1.4.

Some entries belong to a concern rather than to a class: audit, security, SQL. LOG.tag(name) marks them, wherever they come from:

LOG.tag("audit").warn("User {} changed role to {}", user, role);
LOG.tag("sql").debug("{} rows in {} ms", rows, millis);
WARN 18.11.2026 10:30:00 [UserService] [audit] User alice changed role to admin
  • Levels per tag: nanolog.tags=audit=WARN,sql=DEBUG (NANOLOG_TAGS). A rule for the tag of an entry overrides the global level and the package rules, so the audit entries below WARN are dropped wherever they come from, and the SQL entries at DEBUG are written even under nanolog.level=INFO. A tag without a rule follows the level of its class. resetLevels() reads the rules again; LOG.setLevel does not change them.
  • ConsoleLogger writes [audit] after the source class, JsonLogger "tags":["audit"], and Slf4jLogger passes an SLF4J Marker named after the tag. Any logger reads LogEntry.getTags() and may answer ILogger.isEnabled(level, sourceClass, tag); by default it ignores the tag.
  • A tag has the four shapes of LOG.once() at every level: a message with arguments, a lazy message, and both with an exception first. LOG.tag("audit").once() and .atMostEvery(...) limit a tagged statement. An entry has at most one tag; LOG.tag(null) logs without one.
  • A tag costs nothing over an ordinary call. A rule that enables a level for a tag, sql=DEBUG under INFO, makes the level possible, so every call at that level walks the stack, as a package rule does.

Catching exceptions

Since 1.4.

Two patterns repeat in every code base: the try { ... } catch (Exception e) { LOG.error(...) } block that logs and carries on, and the exception that kills a background thread and is printed by the JVM as Exception in thread "pool-1-thread-3", outside the log format, outside JsonLogger and out of sight of MemoryLogger:

LOG.installUncaughtExceptionHandler(); // once, at startup: exceptions that kill threads go into the log

LOG.catching(() -> connection.close()); // best-effort cleanup: ERROR with the stack trace, then carry on
// ERROR 16.11.2026 10:15:02 [Catching] Caught and ignored
// java.io.IOException: Connection reset ...

int retries = LOG.catching(() -> Integer.parseInt(text), 3); // a default value when it fails
// ERROR 16.11.2026 10:15:02 [Catching] Caught, returning 3
// java.lang.NumberFormatException: For input string: "many" ...
  • When to swallow. LOG.catching is for work whose failure must not stop the caller: closing a resource, deleting a temporary file, a best-effort notification or metric. Do not use it where the caller must know about the failure, such as saving data, charging, or anything whose result the next step relies on: let the exception propagate, or handle it.
  • The exception is logged at ERROR with its stack trace, from the class and call site of the LOG.catching call, and the levels apply as usual. The actions may throw checked exceptions (LOG.ThrowingRunnable, LOG.ThrowingSupplier). An Error is not caught, and an InterruptedException is caught with the interrupt flag of the thread set again. Inside a unit a caught exception makes the unit fail, like any ERROR.
  • Threads. LOG.installUncaughtExceptionHandler() installs a default handler that logs Uncaught exception in thread worker-1 with the stack trace, then passes the exception to the handler installed before, so test frameworks and existing handlers still see it; without one, the JVM no longer prints it itself. Installing again changes nothing.
  • The entry of an uncaught exception has the class and call site of the first frame of its stack trace outside the JDK, the code that failed, not the dispatch code of the JVM. The dying thread first writes its breadcrumbs, then the exception, then its units still open, as interrupted.

System.out and System.err

Since 1.4.

Libraries and old code print with System.out.println and e.printStackTrace(). Their lines have no level and no source, miss JsonLogger and are not captured by MemoryLogger. LOG.captureSystemStreams(), or nanolog.captureSystemStreams=true, makes each such line an entry:

INFO 18.11.2026 10:30:00 [LegacyImporter] Imported 120 rows
ERROR 18.11.2026 10:30:01 [LegacyImporter] java.io.IOException: disk full
  • A line of System.out becomes an INFO entry, a line of System.err an ERROR entry; the levels apply, so a line at a disabled level is dropped. The source class and the call site are those of the code that printed; the frames of PrintStream, printf and printStackTrace are skipped.
  • A line ends at \n or \r\n, or when the stream is flushed; a partial line waits, per thread, so the lines of two threads do not mix. Empty lines are dropped, and each line of a stack trace is an entry of its own. The text is kept whole whatever the charset of the platform.
  • No loop: Nanolog writes its own output, the console included, to the streams it found when the capture started, and what a logger prints to System.out while it writes an entry passes straight through.
  • LOG.restoreSystemStreams() puts the streams back, unless something replaced them since; capturing or restoring twice changes nothing.

java.util.logging and System.Logger into Nanolog

Since 1.4.

Many libraries log through java.util.logging, and the JDK through System.Logger. Their lines come in another format on another stream and miss JsonLogger and MemoryLogger. NanologHandler turns their records into entries of Nanolog:

NanologHandler.install();   // once, at startup

or in logging.properties:

handlers=com.nanolaba.logging.NanologHandler
  • install() replaces the handlers of the root logger, its console handler among them, so nothing is printed twice; uninstall() puts them back. A record becomes an entry of the code that called JUL, with the call site and the exception; the message is formatted as JUL formats it, {0} parameters and resource bundles included.
  • SEVERE becomes ERROR, WARNING WARN, INFO INFO, CONFIG and FINE DEBUG, FINER and FINEST TRACE; then the levels of Nanolog apply.
  • JUL decides first: a record below the level of its JUL logger, INFO by default, never reaches Nanolog. To see the FINE records of one library, lower its level in JUL too, com.zaxxer.hikari.level=FINE; lowering the level of the root logger instead makes JUL build a record for every disabled call of every library.
  • System.Logger (Java 9+) reaches the handler as well: the JDK sends it to JUL while the module java.logging is present. Nanolog registers no System.LoggerFinder of its own, which would take over System.Logger in every application that has Nanolog on its classpath.
  • Not together with JulLogger: entries would go round from Nanolog to JUL and back. A record that comes back is dropped, with one [NANOLOG] line.

Caller detection

When no class is passed explicitly, LOG walks the stack and takes the first frame
that does not belong to LOG, LogEntry or an ILogger implementation. On Java 9+ a
StackWalker does it and stops at that frame; on Java 8 Reflection.getCallerClass gives the class of each frame.

  • Nested, anonymous and lambda classes are attributed to their top-level enclosing class.
  • The frame found by the walk is kept as LogEntry.getCaller(): the exact class, method, file and line of the call, including nested classes and lambdas. It costs nothing extra, and it is null when the class was passed explicitly.
  • On Java 9+ the stack walker hands over the class of each frame, so the caller is found exactly whatever class loader it lives in. On Java 8 the internal sun.reflect.Reflection.getCallerClass(int) does the same, and only the frames up to the caller become StackTraceElements (JavaLangAccess.getStackTraceElement); where the two disagree, under Method.invoke, the call falls back to the stack trace of a Throwable. Where neither is available (another JVM, a native image without the metadata for StackWalker), the frames of a Throwable carry only class names: they are resolved through the context class loader of the thread first and the class loader of LOG second, so the detection works when Nanolog lives in a shared loader of an application server and the caller in a web application. A frame neither loader can see or load is skipped, whatever the failure: a missing class, a linkage error such as NoClassDefFoundError, or MissingReflectionRegistrationError from GraalVM in a native image.
  • The stack is walked only for a level the logger may have enabled: LOG first asks ILogger.mayBeEnabled(level), so a level that is off for every class, such as DEBUG under nanolog.level=INFO, costs no walk. LOG.isDebugEnabled() follows the same rule. Once a level is on anywhere, even for one package (nanolog.level.com.acme.db=TRACE), every call at that level walks the stack, because only the class tells whether it is enabled. In hot paths pass the class explicitly: LOG.debug(MyClass.class, ...).
  • Any class implementing ILogger is skipped, so a custom logger that logs through LOG must pass its source class explicitly.
  • If no frame qualifies, the entry is still logged, without a source class and a call site, as with LOG.log(level, null, ...). That happens when the code runs entirely inside an ILogger class, or on Java 8 when the JVM records no stack traces (-XX:-StackTraceInThrowable). Slf4jLogger sends such entries to the ROOT logger.

Logging helpers

Since 1.4.

A helper that logs for others, such as an Audit.record(...) method or a base class of tasks, would be the source of every entry it logs, and its callers would share one rate limit of LOG.once(). Name such helpers in nanolog.caller.skip (or NANOLOG_CALLER_SKIP), class or package names separated by commas:

nanolog.caller.skip=com.acme.Audit,com.acme.logging
  • Their frames are skipped like those of LOG: the entry gets the source class, the call site and the rate limit of the code that called the helper.
  • A class covers its nested classes, and a package its classes and subpackages, by whole segments of the name: com.acme.log does not cover com.acme.logging. A nested class alone is written with $, com.acme.Outer$Helper.
  • A library that wraps LOG cannot rely on the settings of the application: it calls LOG.skipCaller(Helper.class) once, for example in a static initializer. These classes are added to those named in the setting and stay skipped after LOG.init().
  • Slf4jLogger passes the helper to a location-aware backend as the caller boundary, so %file:%line of Logback and %l of Log4j 2 point at the code that called the helper as well.
  • The match is found once per class and cached, so a skipped helper adds no string comparison to later calls. An invalid name, such as com.acme.*, prints a [NANOLOG] diagnostic and is left out; when every frame is skipped, the entry is logged without a source class, as above.

Writing your own logger

ILogger has a single abstract method, so the simplest implementation is a lambda:

LOG.init(entry -> System.out.println(
        entry.getLevel() + " [" + entry.getSourceClass().getSimpleName() + "] " + entry.getFormattedMessage()));

A full implementation also filters levels:

public class CustomLogger implements ILogger {

    @Override
    public void log(LogEntry entry) {
        // write the entry wherever you need: a file, a socket, a queue, ...
        System.out.println(entry.getLevel() + " " + entry.getFormattedMessage());
    }

    @Override
    public boolean isEnabled(LogEntry.LogEntryLevel level, Class sourceClass) {
        // called before the LogEntry is built and before any Supplier is evaluated:
        // return false to suppress entries of this level for this class
        return level != LogEntry.LogEntryLevel.TRACE;
    }

    @Override
    public boolean mayBeEnabled(LogEntry.LogEntryLevel level) {
        // asked before the source class is detected: false spares the stack walk too,
        // so return false only for a level that isEnabled rejects for every class
        return level != LogEntry.LogEntryLevel.TRACE;
    }
}

What a LogEntry carries:

  • getLevel() — TRACE, DEBUG, INFO, WARN or ERROR.
  • getSourceClass() — the detected or explicitly passed class; null only if null was passed.
  • getCaller() — the StackTraceElement of the logging call; null when the source class was passed explicitly.
  • getThrowable() — the exception or null.
  • getMessage() — the raw message object, already resolved from its Supplier.
  • getTimestamp(), getThreadName() — when and in which thread the entry was created, so a logger that writes later or elsewhere still knows.
  • getArgs() — the substitution arguments.
  • isDbg(), isBreadcrumb() — whether the entry comes from LOG.dbg, and whether nanolog.buffer held it back.
  • getFields(), getTrailingFields() — the arguments of LOG.kv(...) by name, and those of them that no {} took.
  • getContext() — the pairs of LOG.context(...) open in the thread that created the entry; an empty map without them.
  • getFormattedMessage() — the final string with {} substituted.

isEnabled(...) is called before the LogEntry is built and before any Supplier is resolved, so returning false skips the whole cost of the message. It does not skip caller detection: for a call without an explicit class the source class is found first, so the stack has already been walked; see Caller detection.

To spare the walk as well, override mayBeEnabled(level), as the example above does: LOG asks it before caller detection, and false means that no class has the level enabled. The default true is always safe; false for a level that isEnabled(...) accepts for some class loses those entries. ConsoleLogger, JsonLogger and CompositeLogger implement it; a subclass that overrides isEnabled(...) but not mayBeEnabled(...) gets true.

A logger that throws does not break the code that logs. The first failure of each logger class prints one line to System.err, for example [NANOLOG] Logger com.acme.AuditLogger threw java.io.UncheckedIOException: disk full; entries it fails to write are printed to System.err. Every entry the logger fails to write then goes to System.err in the ConsoleLogger format, so nothing is lost. If isEnabled(...) throws, the level counts as enabled.

Thread safety and performance

  • The static LOG methods are safe to call from any thread as long as the installed ILogger is; ConsoleLogger and Slf4jLogger are.
  • A logger installed with LOG.init(...) or MemoryLogger.install() is used by every thread from its next logging call, threads that are already running included. Levels may change at any time, through LOG.setLevel(...) and the other level methods or the level setters of ConsoleLogger. The display setters (setShowDate, setDateFormat and the others) are meant for startup, not for concurrent reconfiguration.
  • A call at a level that is off for every class costs one mayBeEnabled check, or one isEnabled check with an explicit class. If a level is on for some package or class, a call at that level without an explicit class costs one stack walk and an isEnabled check even where the level is off, so a single rule such as nanolog.level.com.acme.db=TRACE makes every trace call without a class walk the stack. Message formatting and Supplier evaluation happen only for enabled levels.
  • Measured with JMH on JDK 17 (Ryzen 5 5600X, Windows 10): a call at a level that is off for every class takes about 2 ns without a class and 7 ns with one. The stack walk, the price of a call without a class at a level enabled for some class, takes about 2.5 µs near the top of the stack and 3 µs at 100 frames; Java 8, which has no StackWalker, needs about 5 µs and 8 µs. An enabled line through ConsoleLogger takes under 1 µs, plus the walk if the class is not given. Other JDKs and the method: src/jmh/RESULTS.md.

Using SNAPSHOT versions

Development builds are published to the Sonatype snapshot repository. Add it and depend on the -SNAPSHOT version:

Maven (pom.xml)

<repositories>
    <repository>
        <id>central.sonatype.com-snapshot</id>
        <url>https://central.sonatype.com/repository/maven-snapshots</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
        </snapshots>
    </repository>
</repositories>

<dependency>
    <groupId>com.nanolaba</groupId>
    <artifactId>nanolog</artifactId>
    <version>1.5-SNAPSHOT</version>
</dependency>

Gradle (build.gradle)

repositories {
    maven {
        url 'https://central.sonatype.com/repository/maven-snapshots'
    }
}

dependencies {
    implementation 'com.nanolaba:nanolog:1.5-SNAPSHOT'
}

Related projects

Where Nanolog stands among the loggers you may already know. Compared on 2026-11-18 with the versions in the table headers, from their documentation, their sources and runs on Java 8. ✅ = out of the box, ➖ = partial, ❌ = not supported. Each feature of Nanolog links to the section that describes it.

Static facades

The direct analogues: a static call without a logger field.

Feature Nanolog tinylog 2.8.1 jcabi-log 0.24.3 minlog 1.3.1 Timber 5.0.1
No logger field ✅ ✅ ✅ ✅ ✅
Source class found automatically ✅ ✅ ❌¹ ❌ ✅²
Call site in the output ✅ ✅ ❌ ❌ ➖³
Runtime dependencies one jar api + impl⁴ SLF4J + a backend one jar Android only
Java baseline Java 8 Java 6 Java 8 Java 6 Android API 14
Levels without a configuration file ✅ ✅ ➖⁵ ❌ ❌
Levels changed at run time ✅ ❌⁶ ➖⁵ ✅ ➖⁷
Placeholders {} {}⁸ %s none %s
A trailing exception keeps its stack trace ✅ ❌⁹ ❌¹⁰ ➖¹¹ ❌¹²
A throwing toString() does not break the call ✅ ❌ ❌ ❌¹³ ❌
Lazy messages ✅ ✅ ❌ ❌ ❌
Rate limiting per call site ✅ ❌ ❌ ❌ ❌
Shorter stack traces ✅ ➖¹⁴ ❌ ❌ ❌
JSON lines built in ✅ ✅¹⁵ ➖⁵ ❌ ❌
Context of a thread (MDC) ✅ ✅ ➖⁵ ❌ ❌
Key-value fields of one call ✅ ❌ ❌ ❌ ❌
Capturing entries in tests ✅ ❌ ❌ ❌ ❌
Placeholders checked against the arguments ✅¹⁶ ❌ ➖¹⁷ ❌ ✅¹⁸
Files with rolling ➖¹⁹ ✅ ➖⁵ ❌ ❌
Asynchronous output ❌ ✅ ➖⁵ ❌ ❌
Markers or tags ✅ ✅ ❌ ➖²⁰ ✅
Forwarding to SLF4J or another backend ✅ ➖²¹ ✅ ➖²² ✅
A cheap disabled call, no stack walk ➖²³ ➖²⁴ ✅ ✅ ❌²⁵
Print debugging that names the expression ✅ ❌ ❌ ❌ ❌
Output for coding agents ✅ ❌ ❌ ❌ ❌

¹ jcabi-log: the caller passes this, a class or a name as the source.

² Timber: only DebugTree takes the tag from the calling class.

³ Timber: a subclass of DebugTree can add the method and the line in createStackElementTag.

⁴ tinylog: without tinylog-impl, or when ServiceLoader cannot find it (ProGuard, a fat jar), it prints No logging framework implementation found and logs nothing.

⁵ jcabi-log writes nothing itself: this depends on the SLF4J backend under it.

⁶ tinylog: the configuration is frozen once it is applied; Configuration.set then throws.

⁷ Timber: trees are planted and removed at any time, but there are no levels; a tree filters in isLoggable.

⁸ tinylog: in a call with arguments, text in braces is a DecimalFormat or ChoiceFormat pattern, see the table below.

⁹ tinylog: the exception comes first, Logger.error(e, ...); a trailing one is dropped.

¹⁰ jcabi-log: error(this, "failed %s", id, e) throws IllegalArgumentException; a stack trace goes into the text through %[exception]s.

¹¹ minlog: there are no arguments, only error(message, e).

¹² Timber: the exception comes first; the bundled lint check ThrowableNotAtBeginning flags a trailing one.

¹³ minlog: the caller builds the message, so a throwing toString() throws before minlog is called, even at a disabled level.

¹⁴ tinylog: frames are dropped by package (strip, keep), with no limit on the depth.

¹⁵ tinylog: the json writer, to a file.

¹⁶ Nanolog: at run time with nanolog.strict and in tests, not at build time.

¹⁷ jcabi-log: always on; a mismatch throws out of the logging call.

¹⁸ Timber: the bundled Android Lint checks, at build time.

¹⁹ Nanolog: FileLogger rolls over by size only, with backups; no rolling by date, no compression, no asynchronous writing.

²⁰ minlog: a category string in each call.

²¹ tinylog 2: to java.util.logging and JBoss Logging, and a writer to Logcat; not to SLF4J (slf4j-tinylog goes the other way).

²² minlog: a subclass of Log.Logger, set with Log.setLogger.

²³ Nanolog: a level that is off for every class costs about 2 ns; a level enabled for another package walks the stack, about 3 µs on JDK 17 and 5 µs on Java 8, unless the class is passed.

²⁴ tinylog: with levels per package, a disabled call between the global level and the most verbose package level looks up the caller first.

²⁵ Timber: DebugTree takes the tag from a new stack trace before isLoggable.

Mainstream loggers

The loggers most Java code already uses, and Flogger, which limits the rate per call site.

Feature Nanolog SLF4J 2.0.20 + Logback 1.6.7²⁶ Log4j 2 2.26.1 JUL / System.Logger Flogger 0.9 JBoss Logging 3.6.3
No logger field ✅ ❌²⁷ ➖²⁸ ➖²⁹ ➖³⁰ ❌²⁷
Source class found automatically ✅ ❌²⁷ ✅ ➖³¹ ✅ ❌²⁷
Call site in the output ✅ ✅ ✅ ➖³² ➖³³ ➖³⁴
Runtime dependencies one jar slf4j-api + Logback api + core JDK flogger + a backend one jar³⁵
Java baseline Java 8 Java 11³⁶ Java 8 Java 1.4 / 9 Java 8 Java 11
Levels without a configuration file ✅ ❌²⁶ ➖³⁷ ❌ ❌ ❌
Levels changed at run time ✅ ✅ ✅ ✅ ✅ ➖³⁸
Placeholders {} {} {} {0} %s %s, {0}
A trailing exception keeps its stack trace ✅ ✅ ✅ ❌ ❌³⁹ ❌⁴⁰
A throwing toString() does not break the call ✅ ✅ ✅ ✅ ✅ ➖⁴¹
Lazy messages ✅ ✅ ✅ ✅ ✅ ❌
Rate limiting per call site ✅ ➖⁴² ➖⁴³ ❌ ✅ ❌
Shorter stack traces ✅ ✅ ✅ ❌ ❌ ❌
JSON lines built in ✅ ✅ ➖⁴⁴ ❌ ❌ ➖⁴⁵
Context of a thread (MDC) ✅ ✅ ✅ ❌ ➖⁴⁶ ➖⁴⁷
Key-value fields of one call ✅ ✅ ✅ ❌ ✅ ❌
Capturing entries in tests ✅ ✅ ➖⁴⁸ ❌ ❌ ❌
Placeholders checked against the arguments ✅¹⁶ ➖⁴⁹ ➖⁵⁰ ❌ ✅ ➖⁵¹
Files with rolling ➖¹⁹ ✅ ✅ ➖⁵² ➖⁵² ➖⁴⁵
Asynchronous output ❌ ✅ ✅ ❌ ❌ ➖⁴⁵
Markers or tags ✅ ✅ ✅ ❌ ➖⁵³ ❌
Forwarding to SLF4J or another backend ✅ ✅ ✅ ➖⁵⁴ ✅ ✅
A cheap disabled call, no stack walk ➖²³ ✅ ✅⁵⁵ ✅ ✅⁵⁵ ✅
Print debugging that names the expression ✅ ❌ ❌ ❌ ❌ ❌
Output for coding agents ✅ ❌ ❌ ❌ ❌ ❌

²⁶ slf4j-simple instead of Logback runs on Java 8 and reads levels from system properties, but fixes them at start and has no call site, rolling, JSON or MDC.

²⁷ Lombok 1.18.48 @Slf4j, @Log4j2, @Log, @Flogger and @JBossLog write the field and the class for you, but the field stays, and each class needs the annotation.

²⁸ Log4j 2: LogManager.getLogger().info(...) works inline, but walks the stack and looks up the logger at every call; the docs use a field.

²⁹ java.util.logging: Logger.getGlobal() works from any class, but it is one logger, without levels per class; System.Logger always needs a name.

³⁰ Flogger: FluentLogger.forEnclosingClass() inline walks the stack and creates a logger at every call; the docs prescribe a field.

³¹ java.util.logging: the logger name is passed; each record finds its source class and method.

³² java.util.logging: the class and the method, no line.

³³ Flogger: the system backend prints the class and the method, not the line.

³⁴ JBoss Logging: depends on the backend; the output through java.util.logging gives the class and the method.

³⁵ JBoss Logging: without a backend it writes through java.util.logging.

³⁶ Logback 1.6 needs Java 11; slf4j-api runs on Java 8, and Logback 1.3, the last line for Java 8, is no longer supported.

³⁷ Log4j 2: log4j2.level (LOG4J_LEVEL) sets only the root level of the default configuration.

³⁸ JBoss Logging: through the API of the backend.

³⁹ Flogger: .withCause(e); a trailing exception is reported as an unused argument.

⁴⁰ JBoss Logging: the exception comes first, errorf(e, format, args).

⁴¹ JBoss Logging: through java.util.logging the entry is dropped silently; with Logback the exception reaches the caller.

⁴² Logback: DuplicateMessageFilter, global, by the text of the message.

⁴³ Log4j 2: BurstFilter, global or per appender, by level.

⁴⁴ Log4j 2: JSON Template Layout, a separate jar of the project.

⁴⁵ JBoss Logging: with the jboss-logmanager backend; through java.util.logging there is no JSON and no asynchronous output, and files rotate by size only.

⁴⁶ Flogger: needs flogger-grpc-context; without it the context does nothing.

⁴⁷ JBoss Logging: the MDC API exists, but the output through java.util.logging never prints it.

⁴⁸ Log4j 2: ListAppender in the separate log4j-core-test.

⁴⁹ SLF4J: third-party checks at build time: findbugs-slf4j, Error Prone Support, an IntelliJ inspection.

⁵⁰ Log4j 2: a warning of the status logger, hidden by default, and an IntelliJ inspection.

⁵¹ JBoss Logging: for typed @Message loggers only, by jboss-logging-processor at build time.

⁵² java.util.logging, and Flogger through it: FileHandler rotates by size and count, never by time.

⁵³ Flogger: tags in a scoped context, no markers.

⁵⁴ java.util.logging: the adapters come from SLF4J and Log4j (jul-to-slf4j, log4j-jul).

⁵⁵ Log4j 2 and Flogger: with a logger field; the calls without one of notes 28 and 30 walk the stack every time.

Next to tinylog 2.8.1

tinylog is the closest analogue. The same calls, run on Java 8 with the default configuration of both:

Call tinylog 2.8.1 Nanolog
error("failed {}", id, e) the message only, the stack trace is dropped the message and the stack trace
info("{\"id\": {}}", 42) "id": {}42 {"id": 42}
info("{foo} and {}", "bar") a warning, then bar and {} {foo} and bar
an argument whose toString() throws the exception reaches the caller [FAILED toString()]
changing the configuration after the first log call UnsupportedOperationException LOG.init and LOG.setLevel at any time
packaging api and impl jars, found by ServiceLoader one jar
Java baseline of the next major version tinylog 3, not released yet, drops Java 8 Java 8

When ServiceLoader does not find tinylog-impl, nothing is logged: #126, #135, #140. Java 8 in tinylog 3: #398.

When another logger fits better

  • Log files in production with rolling by date. Rolling by time, compression and retention by age: Logback, Log4j 2, tinylog. FileLogger of Nanolog rolls over by size only.
  • Asynchronous output and high throughput. The asynchronous appenders and loggers of Logback and Log4j 2, the writing thread of tinylog.
  • An ecosystem. Appenders for syslog, databases, message queues and log services, markers and filters, the configuration of Spring Boot: SLF4J with Logback or Log4j 2. Nanolog can write through them with Slf4jLogger.
  • Android. Timber writes to Logcat and checks its format strings with Android Lint. Nanolog is not tested on Android.

Changelog

1.5-SNAPSHOT

  • The [NANOLOG] line of agent mode shows the value of the variable that turned it on up to 64 characters, then ... [+N chars], in double quotes when it would not read as one value, and every [NANOLOG] line prints format characters, such as the bidi override U+202E or the zero-width space U+200B, as escapes such as \u202e. Before, a 5,000-character AI_AGENT made a line of 5,113 characters, and U+202E reversed how the rest of the line read in a terminal that applies bidi.
  • Run summary: a trace one line longer than the 15 shown is shown whole, and so are 11 kinds. Before, ... 1 more lines and ... and 1 more kinds took the place of the one line they hid.
  • Agent mode: its [NANOLOG] line is printed with the first entry, so it describes the logger installed by then: one that the application installed with LOG.init(logger) is named with its call site and keeps its own levels and format. A run that logs nothing prints no such line. Before, the line was printed when LOG initialised and described the default console, which the application then replaced, so the next line could contradict it.
  • A run that logs nothing under agent mode prints nothing and writes nothing: the files of the run log are opened with the first entry, and a run that logged nothing prints no summary, so a command-line tool whose stderr an agent reads, a hook of Claude Code for one, gets only its own lines, and latest.log keeps the run before. LOG.init() stops the run log when its settings no longer turn it on, so a tool can set nanolog.agent=off and call LOG.init() before it logs. Before, such a run added two lines of about 600 characters and an empty latest.log.
  • Logged text cannot make a line read other than it holds: nanolog.console.multiline=escape and indent, the console of agent mode included, the payloads of LOG.content, JsonLogger, the run log and its list of kinds escape the bidi controls (U+202A to U+202E, U+2066 to U+2069) and the tags of Unicode (U+E0000 to U+E007F) as \u202e. latest.errors.log escapes as escape does, the escape sequences of a terminal included. Before, U+202E reversed the rest of a line in a terminal that applies bidi, tags carried text that a person does not see and a language model reads, and ESC sequences reached the terminal of tail -f latest.errors.log.
  • Run summary in a Maven plugin, or wherever the class loader of Nanolog is closed before the JVM exits: the hook loads the classes it needs when it is registered and prints the summary at exit. Before, every build that ran such a plugin under an agent ended with a BootstrapMethodError from the thread nanolog-summary, and the summary was lost. A LOG.unit still open at exit in a run that wrote no entry before needs more classes and is not written then; one [NANOLOG] line says so instead of a stack trace.
  • Agent mode turned off in the middle of the run, by a LOG.init() after nanolog.agent=off: one [NANOLOG] line on the console and last in latest.log and latest.errors.log names that call and says that the run log ends there, after how many entries, and the run summary still ends the run with what it counted before, Run summary until LOG.init() at ... turned it off. The same goes for nanolog.run=off and nanolog.summary=off. Before, the run log that the line of agent mode had named just stopped, as after a crash, and the summary was dropped without a word; in a test JVM one test that did not put the property back did that for every later test.

1.4.1

  • Run summary with forkCount above 1: a Surefire fork that runs several test classes prints one summary after the last of them, through the new SummarySessionListener (JUnit Platform 1.8+). Before, it printed after the first class and missed the rest of the fork.
  • The run log keeps every entry after LOG.init(logger): a logger the application installs, Spring with Slf4jLogger for one, or MemoryLogger.install() gets the run log added, and LOG.getLogger() returns a CompositeLogger of both. A decorator that passes each entry on to the logger LOG.getLogger() returned writes each entry to the file once. Before, the run log stopped at that call, while the run summary still called it the full log.
  • "Logger replaced" no longer attributes a reflective LOG.init to jdk.internal.reflect: a call through reflection belongs to the code that made it, and the fallback caller detection passes over the frames of reflection as the stack walker does. A container named in nanolog.caller.skip, such as org.springframework for MethodInvokingBean, installs the logger for the application, and its calls are never reported.
  • Run summary: warnings and errors are grouped by level and call site, so a call site that builds its messages from data is one kind, shown with its first message and (4 different messages), up to (10+ different messages), instead of filling the list with one kind per value. A call with an explicit class, which has no call site, is still told apart by its message.
  • nanolog.version, the Maven property that holds the version of the dependency, no longer prints Unknown setting when it is set on the command line, where Surefire passes it to the JVMs of the tests as a system property. NANOLOG_VERSION is not reported either.
  • Run log in tests run by Maven or Gradle: a JVM in which Surefire, Failsafe or Gradle runs tests names its own file, runs/<time>-<pid>.log, at the start and in the run summary, so with forkCount above 1 or reuseForks=false each fork points to the file with its own entries for the whole run. Before, every fork pointed to latest.log, which held only the fork that started last. Elsewhere a run names latest.log while it is the file of the run, and its own file once a later run has taken it. The summary is printed in one piece, so the summaries of two forks that end together no longer mix line by line.
  • Run summary: an entry that a test captures with MemoryLogger.capture(), which keeps it from the logger, is no longer counted, so the summary describes the run log it names. Before, a warning that a test provoked and asserted on was listed as a kind and counted, while neither the console nor the run log had it. Entries that NanologExtension holds back are still counted, since the run log gets them when the test ends.
  • NanologExtension also holds back the log of the class outside its tests: the @BeforeAll and @AfterAll methods and the creation of the test instances, where SpringExtension starts the application context. It is printed, framed by --- log of class PaymentServiceTest ---, when a test of the class or the class itself fails, and otherwise goes only to the run log. Before, a passing Spring test class still printed the start-up log of its context.
  • Run summary: every kind of warning and error goes to runs/<time>-<pid>.summary.log next to the run log, with latest.summary.log, one line each, ordered by level and call site so that diff compares two runs. When more than 10 kinds were logged, the line that counts the rest names the file: ... and 2 more kinds of WARN and ERROR; the full list is in .... Before, the kinds past the first ten were counted and written nowhere.
  • Run summary: a message of several lines shows its first line that is not blank, followed by ..., as a message cut at 200 characters. Before, every line break was printed as \u000a, six characters each, and the details filled the line of the kind.
  • Slf4jLogger: the line of LOG.timed(...) and of LOG.unit(name, body) has the call site of that call in the %file:%line of Logback and the %l of Log4j 2. Before, the backend named a frame of Nanolog, Timers.run or LOG.unit. A timer or a unit closed by a try-with-resources block still shows the line where the block ends, since SLF4J has no way to pass a call site that is no longer on the stack; ConsoleLogger, JsonLogger and the run log show the LOG.time or LOG.unit call.
  • The run log no longer changes the levels of a logger the application installs: LOG.isXxxEnabled and the lazy arguments of a call answer for that logger, Slf4jLogger for one, also in agent mode, and the run log gets the entries it takes. Before, the run log, which takes every level, turned every level on after LOG.init(logger), so code that checked a level behaved differently when a coding agent ran it. The short console of agent mode still leaves the rest of its levels to the run log.
  • LOG.unit(level, name), with LOG.unit(level, name, body), writes the line of a failed or interrupted unit at another level than ERROR, such as WARN for a job that is retried, where every ERROR would raise an alert. ok stays INFO; the outcome, the counts and the error.* fields do not change.
  • Agent mode with Slf4jLogger or JulLogger: a LOG.dbg line whose class has DEBUG off in the backend, the root at INFO as in Spring Boot, is printed by Nanolog on System.out in the format of the agent console. Before, the backend dropped it, and only the run log and the list of LOG.dbg calls at exit showed that it ran.

1.4

  • Agent mode: when the environment names a coding agent (AI_AGENT, AGENT, CLAUDECODE, GEMINI_CLI, CODEX_SANDBOX, CODEX_CI, CURSOR_AGENT, VSCODE_AGENT, CLINE_ACTIVE), the console of the default logger shows WARN and above, one line per entry, without dates or colours and with short stack traces, LOG.dbg prints whatever the levels, the run log is on, and one [NANOLOG] line says so and names the file. nanolog.agent=auto|on|off decides; an explicitly set level or display setting wins.
  • Documentation: what agent mode saves, measured in tokens. Four runs of a small project in src/tokens, with the script that repeats them; a failing test run printed 1,022 tokens instead of 13,577 (o200k_base). See Fewer tokens.
  • Run summary, nanolog.summary=on|off|errors, on by default in agent mode: the run ends with the counts by level, each kind of warning and error with its call site and count, the trace of the first error, the LOG.dbg calls that ran and the path of the run log. The summary is printed last so that it survives when an agent keeps only the tail of the output. In test runs SummaryListener, which the JUnit Platform loads by itself, prints it and the list of LOG.dbg calls when the tests have run, because Surefire drops what a shutdown hook of its forked JVM prints.
  • Run log for agents: with nanolog.run=on every entry of the run also goes to target/nanolog/latest.log (Gradle: build/nanolog, otherwise .nanolog), warnings and errors to latest.errors.log one line each, and the absolute path is printed when LOG initialises. Each run writes runs/<time>-<pid>.log, latest.log is a hard link to it, the last 10 runs are kept. nanolog.run.dir, nanolog.run.format=json, nanolog.run.keep, nanolog.run.maxSize.
  • LOG.dbg(expression) prints the expression as written in the source, its value and type, and the call site, and returns the value; LOG.dbg(a, b, ...) prints several, LOG.dbg() that the line was reached. Without the source only the values are printed. ConsoleLogger marks the line DBG, JsonLogger adds "dbg":true, LogEntry.isDbg() tells the entry apart; nanolog.sources names the source directories.
  • Objects whose class has no toString() of its own are printed field by field instead of Invoice@2f92e0f4: always in LOG.dbg, and in {} arguments with nanolog.dump=auto. Classes of the JDK are never reflected into, so nothing needs --add-opens on JDK 17+; cycles, depth, items and string length are limited, and every cut says what it left out; fields named like secrets print ***; records show their components, proxies only their class name.
  • Leftover LOG.dbg calls: when the JVM exits, one [NANOLOG] line lists the call sites that printed; nanolog.dbg=off silences the calls, nanolog.dbg=fail reports each one as a diagnostic that fails MemoryLogger.assertNoDiagnostics(); NanologChecks.assertNoDbgCalls("src/main/java") fails a test while the sources call LOG.dbg, with the file, line and code of each call. MemoryLogger.assertNoDiagnostics() now says Nanolog reported instead of strict mode reported.
  • Wide events: LOG.unit("checkout") opens a unit of work that writes one canonical log line per request or job when it closes, checkout ok 182 ms orderId=A-17 warn=1: the outcome (ok, error, interrupted), the duration, the fields of put(...), the counts of warnings and errors logged inside it and, for a failed unit, error.type, error.message and an error.key that stays the same between runs. Units nest (parent=), cross executors with LOG.wrap and are written as interrupted when the run ends while they are open; nanolog.unit.sample / nanolog.unit.slowMs sample the fast successful ones; run(...) and LOG.unit(name, body) record a thrown exception.
  • Settings that Nanolog does not know are reported when LOG initialises instead of being ignored: a mistyped nanolog.* system property, NANOLOG_* environment variable or key of nanolog.properties prints [NANOLOG] Unknown setting "nanolog.levle" (system property); did you mean "nanolog.level"?, a key of the file without the nanolog. prefix is reported as ignored, and NANOLOG_LEVEL_COM_ACME points to NANOLOG_LEVELS. Keys of a custom logger under a namespace of its own are left alone.
  • NanologExtension, a JUnit 5 extension: the log of a test is held back and printed only when the test fails, framed by --- log of PaymentServiceTest.chargeIsRetried ---; a passing or aborted test writes it only to the run log. Parallel tests keep their logs apart, and nanolog.junit.output=failed|all|none decides what is printed.
  • nanolog.console.multiline (setMultiline) for ConsoleLogger: indent starts every line of an entry after the first with a tab, so a message cannot forge an entry; escape writes line breaks as \r and \n, so an entry and its stack trace are one physical line; both write other control characters, terminal escape sequences among them, as \u001b. keep, the default, changes nothing; agent mode uses escape.
  • Coloured level words on a terminal, nanolog.console.color=auto|always|never (setColor): red ERROR, yellow WARN, green INFO, dim DEBUG and TRACE, magenta DBG. auto, the default, colours only when standard output is a terminal, honours NO_COLOR, FORCE_COLOR and TERM=dumb, and stays off on Windows and in agent mode; pipes, files, the run log and JsonLogger never get escape codes.
  • java.util.logging both ways: JulLogger (nanolog.logger=com.nanolaba.logging.JulLogger) writes the entries to JUL, to the logger of the source class with the call site, and asks JUL for the levels; NanologHandler.install() or handlers=com.nanolaba.logging.NanologHandler turns the records of JUL, and so of System.Logger, into entries of the code that called it. A loop between the two is reported and cut.
  • GraalVM native image and Android: the jar carries the metadata of a native image (META-INF/native-image: the constructors of the loggers, the stack walker, nanolog.properties) and rules for R8 and ProGuard (META-INF/proguard/nanolog.pro), so neither needs setup; CI builds and runs a native image on GraalVM 21 and 25.
  • FileLogger: nanolog.logger=com.nanolaba.logging.FileLogger with nanolog.file=logs/app.log appends the entries to a file, in the text format of ConsoleLogger or the JSON lines of JsonLogger. Each entry is written through at once, or with nanolog.file.flush=buffer kept until LOG.flush(); the file rolls over at nanolog.file.maxSize, with nanolog.file.backups. LOG.flush() and ILogger.flush() are new.
  • A real module descriptor: on Java 9+ the jar is the module com.nanolaba.nanolog, from META-INF/versions/9/module-info.class of a multi-release jar, so jlink accepts it; the module needs only java.base.
  • LOG.captureSystemStreams() and nanolog.captureSystemStreams=true turn the lines printed to System.out and System.err into INFO and ERROR entries with the source and call site of the code that printed, e.printStackTrace() included, without a loop through the console.
  • Calls from Kotlin are checked: CI compiles the calls of LOG in every form from Kotlin, so an overload that is ambiguous for Kotlin, as in tinylog, fails the build.
  • Slf4jLogger is tested against SLF4J 1.7 as well as 2.x: CI runs the tests once more with slf4j-api and slf4j-simple 1.7.36.
  • A library that replaces the logger of the application is reported: when code of another organization (the first two segments of the package) replaces a logger installed with LOG.init(logger), a [NANOLOG] line names both call sites. LOG.lock() and nanolog.logger.lock=true keep the installed logger and turn later LOG.init calls into no-ops with such a line; MemoryLogger.install() still works under the lock.
  • Documentation: a nanolog.properties in src/test/resources replaces the one in src/main/resources in tests, as a whole file, not merged.
  • Several nanolog.properties on the classpath, at least one of them in a jar, are reported with one [NANOLOG] line that lists them and names the one that was read: a library that ships its own file no longer wins over the file of the application without a word. Two directories, such as the main and the test resources, stay quiet.
  • Tags: LOG.tag("audit").warn(...) marks the entries of a concern rather than of a class, and nanolog.tags=audit=WARN,sql=DEBUG sets levels per tag, which take precedence over the levels of the class. ConsoleLogger writes [audit], JsonLogger "tags":["audit"], Slf4jLogger passes an SLF4J Marker; LogEntry.getTags() and ILogger.isEnabled(level, sourceClass, tag) are new.
  • Lazy arguments: LOG.debug("Stats: {}", LOG.lazy(() -> summarize(stats))) computes one argument only if the level is enabled, once, and keeps the template for strict mode, JsonLogger and assertTemplateLogged.
  • nanolog.console.sourceLength (setSourceLength) abbreviates a fully qualified source name like %logger{n} of Logback: com.acme.billing.payments.PaymentService becomes c.a.b.p.PaymentService at 20 characters.
  • nanolog.console.timeZone (setTimeZone) sets the time zone of the ConsoleLogger timestamps, such as UTC or Europe/Berlin; an unknown ID is reported instead of being taken for GMT. nanolog.console.dateFormat=iso stands for the ISO 8601 pattern with milliseconds and the offset of the zone.
  • Context providers: LOG.addContextProvider(() -> ids) and nanolog.context.provider=com.acme.TraceIdProvider add the keys of a context of their own, such as the trace ID of OpenTelemetry, to every entry, after the pairs of LOG.context, which win. A provider is asked only for an enabled entry; one that throws is reported once and the entry is logged without its keys.
  • Logging helpers: nanolog.caller.skip=com.acme.Audit,com.acme.logging and LOG.skipCaller(Helper.class) skip the frames of classes and packages that log for others, so an entry logged through Audit.record(...) gets the source class, call site and rate limit of the code that called the helper, and Slf4jLogger passes the helper to Logback and Log4j 2 as the caller boundary.
  • Strict mode reports two more mistakes, with the call site: an argument that repeats the message of the exception logged with it, LOG.error("Failed: {}", e.getMessage(), e), and a call site seen with two different templates, that is, a template built from data, such as LOG.info("User " + id + " from {}", ip). Like the placeholder check, both reach ILogger.onDiagnostic and fail MemoryLogger.assertNoDiagnostics(); calls without arguments are not checked.
  • README: Related projects, a comparison with tinylog, jcabi-log, minlog, Timber, SLF4J with Logback, Log4j 2, java.util.logging, Flogger and JBoss Logging, with the calls that behave differently in tinylog.
  • Faster caller detection on Java 8: Reflection.getCallerClass gives the class of each frame and only the frames up to the caller are built, so a call without a class at a level enabled for some class costs about 5 µs instead of 20 near the top of the stack and 19 µs instead of 270 at 500 frames; the stack trace of a Throwable stays the fallback.
  • Secrets: LOG.secret(token) is written as *** by every logger and keeps no value; fields and context values whose key names a secret, password, token, apikey and the others of nanolog.redact, are masked when the entry is created; a shown LOG.content masks keys of model providers, AWS keys, bearer tokens and JSON web tokens.
  • LOG.time("Load users") and LOG.timed("Count users", () -> ...) time a block: Load users took 123 ms with the fields timer and duration_ms; a level that is off reads no clock, and the lambda form reports and rethrows an exception.
  • nanolog.console.repeats=collapse (setRepeats), the default in agent mode: consecutive repeats of an entry become one line with a count, (repeated 41 more times in 20.3 s), written when another entry comes, the logger is replaced or the run ends, and every ten seconds while the repeats go on; the run log, JsonLogger and MemoryLogger keep every entry.
  • nanolog.diagnostics=once|all|off: each distinct [NANOLOG] diagnostic is printed once per JVM by default, configuration mistakes and the findings of strict mode at each call site included, so a ConsoleLogger created again does not repeat them; all prints every one, off none. A diagnostic about an invalid value says where it was set: a system property, an environment variable or the file. The run summary and the other notices are not affected.
  • nanolog.console.showSourceLine (setShowSourceLine): the source line of the call under each entry, > LOG.warn("Charge of {} failed", amount);, and under the first three frames of a stack trace outside the JDK. The line is found as LOG.dbg finds its source and left out when the source is missing or stale; JsonLogger adds "source" to "caller". A part of a ConsoleLogger line that follows a line break no longer starts with a space.
  • LOG.catching(() -> cleanup()) logs an exception at ERROR with its stack trace and carries on, LOG.catching(() -> parse(s), -1) returns a default instead; checked exceptions are allowed, an Error is not caught, an interruption is kept. LOG.installUncaughtExceptionHandler() logs the exceptions that kill threads, from the first frame outside the JDK, then passes them to the previous handler; the dying thread writes its breadcrumbs and its open units too.
  • README: Logging LLM calls, a LangChain4j listener and a Spring AI advisor that log one line per model call with the OpenTelemetry gen_ai.* field names, the prompt and the completion as LOG.content, and a transcript at DEBUG.
  • Payloads: LOG.content(prompt) writes a prompt, a response or a request body as [content 1834 chars #3f2a9c1b], its length and a hash keyed per JVM, unless nanolog.content=truncate:<characters> or show says otherwise, for all classes or, through nanolog.content.<package or class>, for some. The text is taken when the entry is created and always escaped against forged lines; in JSON fields a hidden payload is {"content_len":1834,"content_hash":"3f2a9c1b"}.
  • Breadcrumbs: nanolog.buffer=DEBUG holds DEBUG and TRACE entries back, the newest 200 per thread (nanolog.buffer.size), and writes them before the next ERROR under --- 37 earlier DEBUG entries ---; inside LOG.unit the unit drops them when it succeeds and writes them after its line when it fails. Held-back levels count as enabled, entries are snapshots with the time of their call, and JsonLogger marks them "breadcrumb":true.
  • Fields: LOG.kv("orderId", id) names an argument. In a {} it prints its value; without one ConsoleLogger and Slf4jLogger append orderId=A-17 to the message and strict mode does not count it. JsonLogger writes every field into a "fields" object whose numbers and booleans keep their type, so jq selects entries by them, and LogEntry.getFields() gives them to any logger.
  • Context: try (LOG.Context c = LOG.context("requestId", id)) { ... } adds requestId=r-17 to every entry the thread logs inside the block, nested scopes put the previous value back, and LOG.wrap(task) carries the context into a task that another thread runs. ConsoleLogger prints the pairs after the message (nanolog.console.showContext), JsonLogger writes a "context" object whose numbers and booleans keep their type, Slf4jLogger puts the pairs into the MDC for %X{requestId}, and LogEntry.getContext() gives them to any logger.
  • MemoryLogger.capture() and captureForwarding() capture the entries of the current thread only, every level, while the logger of LOG stays installed for the other threads, so tests that run in parallel in one JVM can assert on their own log. The findings of strict mode on that thread reach the capture as well.

1.3

  • Levels change while the application runs, thread-safely: LOG.setLevel(level), LOG.setLevel(name, level), LOG.clearLevel(name), LOG.resetLevels(), and LOG.withLevel(name, level) for a try block. The level is a LogEntryLevel or a string such as "OFF", as in the settings. ConsoleLogger, JsonLogger and CompositeLogger implement the new ILevelControl, and the level setters of ConsoleLogger may now be called while other threads log.
  • LOG.once() and LOG.atMostEvery(period, unit) limit a statement to its first call or to one entry per period, keyed by the call site. The next entry that gets through carries the number of skipped calls, LogEntry.getSkippedCount(), which ConsoleLogger, JsonLogger and Slf4jLogger print.
  • Shorter stack traces in ConsoleLogger and JsonLogger: nanolog.exception.exclude collapses runs of frames from packages such as org.junit or jdk.internal.reflect into ... N frames excluded, nanolog.exception.maxFrames caps the frames of each throwable. Without them the output is that of printStackTrace, as before.
  • MemoryLogger: assertNoneAtOrAbove(level), assertLogged(level, text) and assertTemplateLogged(level, template) fail with an AssertionError that lists every captured entry, stack traces and call sites included; getEntries(Class) selects the entries of one source class.
  • Strict mode reaches tests: every finding also goes to the installed logger through the new ILogger.onDiagnostic, every occurrence rather than the first one of a template, and MemoryLogger.assertNoDiagnostics() fails on them. CompositeLogger forwards them.
  • ConsoleLogger, JsonLogger: nanolog.console.stream (or setStream) chooses the stream of each level: out sends everything to standard output, so java -jar app.jar | jq keeps the ERROR lines, err sends everything to standard error, err@WARN warnings and errors. The default err@ERROR is the former behaviour.
  • ConsoleLogger: setShowThread(true) or nanolog.console.showThread=true prints the name of the thread after the date, INFO 16.11.2026 10:15:02 [main] [PaymentService] Charged 42. Off by default, so the format of existing output does not change.
  • Calls without an explicit class no longer walk the stack when their level is off for every class: LOG asks the new ILogger.mayBeEnabled(level) first. ConsoleLogger, JsonLogger and CompositeLogger answer it from their switches, package rules and delegates; other loggers keep the default true and work as before.
  • On Java 9+ caller detection uses StackWalker: it stops at the calling frame and loads no class by name, so a call without an explicit class costs about 3 µs instead of 9 to 26 µs on JDK 17 and hardly grows with the depth of the stack. A caller in a class loader that neither the context loader nor the loader of Nanolog can see is now found exactly instead of being skipped. Java 8 keeps the Throwable walk.
  • A logger that throws no longer breaks the logging call: the failure is reported once per logger class with a [NANOLOG] line, and the entry is printed to System.err instead. Inside CompositeLogger a throwing delegate no longer stops the others.
  • A lazy message whose Supplier throws no longer escapes from the logging call: the entry is logged with the message [FAILED supplier: <exception>].
  • When no stack frame qualifies as the caller (-XX:-StackTraceInThrowable, or code running entirely inside an ILogger), the entry is logged without a source class instead of throwing IllegalStateException.
  • Caller detection no longer lets an error from a class loader escape: a frame whose class fails to load with NoClassDefFoundError, MissingReflectionRegistrationError from GraalVM or any other throwable is resolved through the other loader or skipped.
  • A logger installed with LOG.init(...) or MemoryLogger.install() is now guaranteed to be seen by threads that are already logging; before, a test could miss entries logged from an executor thread.
  • ConsoleLogger: an anonymous or local source class passed explicitly is printed as [Foo$1] instead of [] or [null]; LogEntry.toString() names it too.
  • A [NANOLOG] diagnostic is always one line. Control characters in the values it repeats, such as a level passed to LOG.setLevel from a request, an exception message or a template, are printed as \u000a escapes, so such a value cannot forge a line of the log.
  • Documentation: the Slf4jLogger section no longer says that MDC works with every backend; slf4j-simple and slf4j-nop discard MDC values.
  • Documentation: ILogger.isEnabled no longer promises that returning false skips the whole cost of a call; caller detection has already walked the stack by then.
  • JMH benchmarks in src/jmh, built with mvn -P benchmark test-compile exec:exec, with results for JDK 8 to 25 in src/jmh/RESULTS.md; the README quotes the measured costs.

1.2

  • A trailing Throwable that no {} consumes becomes the exception of the entry, as in SLF4J: LOG.error("Failed", e) and LOG.error("Failed {}", id, e) no longer drop the stack trace.
  • LogEntry.getCaller() returns the frame of the logging call, and ConsoleLogger.setShowLocation(true) prints it as [PaymentService.charge(PaymentService.java:87)].
  • ConsoleLogger reads its levels and options from properties and environment variables: nanolog.level, nanolog.level.<package or class>, nanolog.levels and nanolog.console.*. Every property, nanolog.logger and nanolog.config included, can be set as an environment variable (NANOLOG_LEVEL), which beats nanolog.properties.
  • JsonLogger writes one JSON object per line. LogEntry.getTimestamp() and LogEntry.getThreadName() tell when and where an entry was created.
  • MemoryLogger captures entries in tests (try (MemoryLogger log = MemoryLogger.install()) { ... }), CompositeLogger sends entries to several loggers.
  • nanolog.strict=true reports calls whose {} placeholders and arguments do not match, once per template, with the call site.
  • Slf4jLogger: location-aware backends (Logback, Log4j 2) report the code that called LOG in %file:%line and %l, instead of Slf4jLogger.log.
  • ConsoleLogger: a throwable whose toString() throws no longer escapes from the logging call; it is printed as [FAILED printStackTrace()].
  • The whole public API has Javadoc, and the build fails on a missing comment.
  • llms.txt and the agent skill skills/nanolog/SKILL.md give coding agents the rules of the library; both are generated with the README.

1.1

  • New overloads LOG.info(throwable, "... {} ...", args) and LOG.info(sourceClass, throwable, "... {} ...", args) for every level: an exception together with a parameterized message.
  • nanolog.properties: only nanolog. keys are copied into system properties; other keys are ignored.
  • Slf4jLogger: a null source class goes to the ROOT logger instead of throwing; an entry without a message no longer logs the word null.
  • Caller detection resolves classes through the context class loader first and skips frames it cannot see, instead of failing in application servers and plugin frameworks.
  • ConsoleLogger: timestamp formatting is thread-safe.
  • A broken toString() inside an Object[] argument no longer propagates to the caller.
  • A null context class loader at startup is tolerated.
  • The diagnostic for a missing configuration file names the right property.
  • The jar declares Automatic-Module-Name: com.nanolaba.nanolog.

1.0

First release.

Contributing

License

Apache License 2.0.


Generated with nanolaba/readme-generator

Yorumlar (0)

Sonuc bulunamadi