nanolog
Health Warn
- License — License: Apache-2.0
- Description — Repository has a description
- Active repo — Last push 0 days ago
- Low visibility — Only 6 GitHub stars
Code Pass
- Code scan — Scanned 12 files during light audit, no dangerous patterns found
Permissions Pass
- Permissions — No dangerous permissions requested
No AI report is available for this listing yet.
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.
[ en | ru ]
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_AGENTruns the program, the console keepsWARN,ERRORandLOG.dbg, and the full log goes totarget/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())printsorder.total() = 129.90 (BigDecimal)with the file and line of the call and returns the value, likedbg!in Rust and icecream in Python; objects withouttoString()are shown field by field instead ofOrder@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-apiis needed only if you useSlf4jLogger. - SLF4J-style placeholders.
{}with escaping, array rendering and sane handling of missing or extra arguments. - JSON lines and tests built in.
JsonLoggerwrites one JSON object per line forjqand log collectors;MemoryLoggercaptures 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, andLOG.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
- 1 Installation
- 2 Quick start
- 2.1 API at a glance
- 3 Fewer tokens: logs for AI coding agents
- 4 Agent-driven development
- 5 Print debugging:
LOG.dbgprints the expression and its value - 6 Wide events: one line per request (canonical log lines)
- 7 Timing a block
- 8 Breadcrumbs: DEBUG only when something fails
- 9 Choosing a logger
- 9.1 ConsoleLogger
- 9.2 Levels and options without code
- 9.3 Changing levels at run time
- 9.4 Shorter stack traces
- 9.5 JsonLogger
- 9.6 FileLogger
- 9.7 Slf4jLogger
- 9.8 JulLogger
- 9.9 MemoryLogger and CompositeLogger
- 10 Logs in tests: only the failing ones
- 11 Message formatting
- 12 Logging payloads safely
- 13 Masking secrets
- 14 Logging LLM calls
- 14.1 LangChain4j
- 14.2 Spring AI
- 15 Context: tag the lines of one request
- 15.1 Context providers
- 16 Rate limiting
- 17 Tags
- 18 Catching exceptions
- 19 System.out and System.err
- 20 java.util.logging and System.Logger into Nanolog
- 21 Caller detection
- 21.1 Logging helpers
- 22 Writing your own logger
- 23 Thread safety and performance
- 24 Using SNAPSHOT versions
- 25 Related projects
- 25.1 Static facades
- 25.2 Mainstream loggers
- 25.3 Next to tinylog 2.8.1
- 25.4 When another logger fits better
- 26 Changelog
- 27 Contributing
- 28 License
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 thatnanolog.loggernames, the stack walker of caller detection and the resourcenanolog.properties. CI builds a native image on GraalVM 21 and 25 that logs throughConsoleLoggerand throughJsonLoggerchosen with-Dnanolog.logger. A class of your own named innanolog.loggerornanolog.context.providerneeds its constructor registered by you, and a class thatLOG.dbgornanolog.dumpprints field by field needs its fields registered.LOG.dbgprints 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.

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
WARNand 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.logholds 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()andLOG.atMostEvery(...)thin out loops and polls, andLOG.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 andLOG.info(...). Nothing goes stale when the code is moved or the class is renamed. - Output from the first run.
ConsoleLoggerworks without configuration and prints every level,TRACEincluded; in agent mode the console keepsWARNand above, and the run log every level. ALOG.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=INFOcuts the noise once the first run is read, and-Dnanolog.level.com.acme.payments=DEBUGturns detail up for one package, even if the startup code switchedDEBUGoff. 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=escapekeeps every entry, its stack trace included, on one physical line, andindentstarts every further line of an entry with a tab, so user data cannot forge an entry. Agent mode usesescape. The output is simple togrepand to match against the sources. WithsetShowLocation(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:%linereports the same call site. - Output a script can parse.
-Dnanolog.logger=com.nanolaba.logging.JsonLoggerswitches to one JSON object per line, with the timestamp, thread, call site and stack trace as fields, ready forjqor 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, anullor a wrong number of{}arguments ends up as a readable message, not as an exception. In test runs,-Dnanolog.strict=truestill 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()andLOG.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 writestarget/nanolog/latest.log, with warnings and errors inlatest.errors.log, and prints the path. The agent reads the file instead of running a five-minute suite again for everygrep, and follows a background server withtail -f. See Run log. - Debug prints do not stay behind. A forgotten
System.out.printlnlooks like any other output; aLOG.dbgcall has a name of its own. The run lists the ones that printed,nanolog.dbg=offsilences them in production, andNanologChecks.assertNoDbgCallsfails 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,nooroff:AI_AGENTandAGENT, the convention proposed in agents.md #136, thenCLAUDECODE,GEMINI_CLI,CODEX_SANDBOX,CODEX_CI,CURSOR_AGENT,VSCODE_AGENTandCLINE_ACTIVE. Claude Code, for one, setsAI_AGENTandCLAUDECODE. Environment variables are lost acrosssudo,docker runandssh, so detection is a hint:nanolog.agent=onoroff(NANOLOG_AGENT) decides instead. - The console.
WARNand above, unlessnanolog.levelor 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.excludeandnanolog.exception.maxFramesreplace these defaults. LOG.dbgprints whatever the levels: the agent put it there to see the value. WithSlf4jLoggerorJulLogger, aLOG.dbgline that the backend would drop, its class havingDEBUGoff there, is printed by Nanolog onSystem.outin the format of the console above.nanolog.dbg=offstill 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=offturns 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=offturns it off. - Only Nanolog's own output changes. The defaults above apply to the default logger,
ConsoleLoggerorJsonLogger; a logger set withLOG.init(logger), or another class named bynanolog.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 withMemoryLogger, or setNANOLOG_AGENT=offfor the test JVM (environmentVariablesof 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 ofmain, orNANOLOG_AGENT=offin its launcher. OnceLOGhas initialised, the same property and thenLOG.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 oflatest.logdoes 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 setsnanolog.agent=offand does not put it back turns agent mode off for every later test; the line names theLOG.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; theLOG.dbgcalls that ran; the path of the run log. It counts the entries that reach the logger: a warning that a test provokes insideMemoryLogger.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 withdiff. 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.logis a second name of the list of the run inlatest.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;errorsprints it only after aWARNorERROR;off, the default otherwise. It goes toSystem.erronce per JVM: when JUnit has run the tests of that JVM, throughSummarySessionListenerandSummaryListener, 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, withforkCountabove 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 withtestLogging.showStandardStreams = true. A run that logged nothing prints no summary. ALOG.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.
SummaryListenerandSummarySessionListenerare compiled against the JUnit Platform Launcher API, which a test run provides, so Nanolog still has no dependencies. A shaded jar that keepsMETA-INF/services/org.junit.platform.launcher.TestExecutionListenerororg.junit.platform.launcher.LauncherSessionListenermust keep the class it names too, or JUnit stops with aServiceConfigurationError.
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/nanologin a Maven module,build/nanologin a Gradle one,.nanologotherwise, which gets a.gitignore;nanolog.run.dirnames another directory. The absolute path is printed with the first entry, because search tools often skip ignored*.logfiles. - What.
latest.logholds every entry, with the thread and the call site;nanolog.run.format=jsonwrites the lines ofJsonLoggerinstead, ready forjq.latest.errors.logholds eachWARNandERRORas one line, cheap to follow withtail -f, written asnanolog.console.multiline=escapewrites 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 whenlatest.logkeeps line breaks. With the run summary on,latest.summary.loglists every kind of warning and error of the run at its end, see Run summary. - History. Each run writes
runs/<time>-<pid>.log, andlatest.logis 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 takenlatest.log, the path of the run's own file is printed instead oflatest.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 (forkCountabove 1) or one after another (reuseForks=false), and each takeslatest.logfrom the one before, so each fork names the file with its own entries. - Levels. The run log reads
nanolog.leveland the package rules asConsoleLoggerdoes, andLOG.setLevelchanges both. It takes what the logger takes, soLOG.isDebugEnabled()and the lazy arguments of a call answer as they would without it: a logger installed withLOG.init(logger)or named bynanolog.logger,Slf4jLoggerfor 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 withLOG.init(logger)orMemoryLogger.install(), Spring'sSlf4jLoggerfor one: the run log is added to it, andLOG.getLogger()returns aCompositeLoggerof both. A decorator that passes each entry on to the loggerLOG.getLogger()returned, andMemoryLogger.installForwarding(), write each entry to the file once. ALOG.init()whose settings no longer turn the run log on,nanolog.agent=offwithoutnanolog.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, orAgent 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@nanologClaude Code, Cursor, Codex and the other agents that read Agent Skills, with the
skillsCLI (-a claude-codelimits it to one agent):npx skills add nanolaba/nanologBy 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.mdOther 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/classesleads tosrc/main/java,target/test-classestosrc/test/java, Gradle'sbuild/classes/java/maintosrc/main/java, and the same for Kotlin; for other layouts the usual directories of the working directory are tried.nanolog.sources=dir1,dir2names 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
dbgcalls, 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, asInvoice{id=17, ...}does. - It is a
DEBUGentry:nanolog.leveland package rules apply, and a level that is off everywhere costs no stack walk. In agent mode it prints whatever the levels; whenSlf4jLoggerorJulLoggerwould pass it to a backend that hasDEBUGoff for the class, the console of Nanolog prints it instead.ConsoleLoggermarks itDBGand prints the call site even withoutshowLocation,JsonLoggeradds"dbg":true, any logger tells it apart withLogEntry.isDbg().LOG.once().dbg(...)andLOG.atMostEvery(...).dbg(...)limit it like any other statement. dbgis meant to be temporary: a debug print that names its values replaces a series ofSystem.out.printlncalls, 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 andOptionalare walked through their public API, any other JDK value prints itstoString(). So the dump needs no--add-openson JDK 17+ and cannot fail withInaccessibleObjectException, unlike Commons LangReflectionToStringBuilder. 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 generatedtoString()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 printsCustomer{... (+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 todbgitself is never cut. - A field or a string map key whose name contains
password,passwd,secret,token,apiKey,credentialorauthorization, ignoring case,_and-, prints***unless it isnull, soaccessTokenandX-Api-Keyare hidden too. - Proxies and lambdas print only their class name: a Hibernate proxy (
$HibernateProxy$), a CGLIB or Javassist class ($$) or ajava.lang.reflect.Proxyis never called, so printing an entity never triggers lazy loading. - Nothing escapes: a failure while dumping a value prints
[FAILED dump()], as a brokentoString()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.assertNoDbgCallsreads the.javaand.ktfiles under the directories as text: no compiler plugin, no annotation processor, no extra dependency. It findsLOG.dbg(...),LOG.once().dbg(...),LOG.atMostEvery(...).dbg(...),LOG::dbgand a static import ofLOG.dbg, also split over lines, and skips comments, strings and text blocks, so a Javadoc that showsLOG.dbgdoes 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 ofput(...)and the counts of warnings (warn) and errors (error) logged inside the unit, in any thread it was carried into. Its fields areunit,outcome,duration_msand the rest, soJsonLoggerwrites"fields":{"unit":"checkout","outcome":"ok","duration_ms":182,...}andjqselects the failed units by.fields.outcome. - The outcome is
ok, anINFOline, orerror, anERRORline, once anERRORentry was logged inside the unit orfail(e)was called. A failed unit addserror.type,error.messageanderror.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 everyERRORwould raise an alert:okstaysINFO, and the outcome, the counts and theerror.*fields do not change, sooutcome=errorstill finds the unit. - Exceptions.
close()cannot see an exception that leaves a try-with-resources block: catch it and callu.fail(e), or letrun(...)do it.LOG.unit("import", () -> importFile(file))andLOG.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 outcomeinterrupted. That happens before the run summary, which therefore counts it and lists a failed unit asunit <name>. - Sampling.
nanolog.unit.sample=0.05writes 5% of the units that succeed fast and every failed one, andnanolog.unit.slowMs=500always 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.unitcall (for Logback and Log4j 2, seeSlf4jLogger) and the context of the thread. It follows the levels: anokunit of a class set toWARNwrites nothing, a failed one is still written, unlessLOG.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=DEBUGa failed unit is followed by theDEBUGentries 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
ThreadLocalread 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
timerandduration_ms, as a unit of work has itsduration_ms, soJsonLoggerwrites"fields":{"timer":"Load users","duration_ms":123}. Its source class and call site are those of theLOG.timecall; for the%file:%lineof Logback and the%lof Log4j 2, seeSlf4jLogger. - 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)writesCount users failed after 12 mswith 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,INFOorWARN, and the levels below it are held back too;offis 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()istrueand the message is built even when the logger hasDEBUGoff, as withnanolog.level=INFOin production. Building messages that are mostly thrown away costs what logging atDEBUGcosts. - Outside units each thread has its own buffer, which its next
ERRORwrites. 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
JsonLoggeradds"breadcrumb":true. LOG.dbgis never held back, and a capture ofMemoryLoggergets 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:
Programmatically — pass any
ILoggerimplementation toLOG.init(...)at application startup:LOG.init(new Slf4jLogger());Via a system property — the fully qualified name of a class with a public no-arg constructor:
-Dnanolog.logger=com.nanolaba.logging.Slf4jLoggerVia a configuration file — put
nanolog.propertieson the classpath:nanolog.logger=com.nanolaba.logging.Slf4jLoggerWhen
LOGinitialises, the keys of the file with thenanolog.prefix are copied
into system properties without overwriting the ones already set via-Dor an environment variable.
Other keys are ignored, and each one is reported (see below). The file path can be overridden with thenanolog.configproperty.
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 ananolog.propertiesinsrc/test/resourcesreplaces the one insrc/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-Dor an environment variable, for example in thesystemPropertyVariablesof 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.initreplaces 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 withLOG.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, asMethodInvokingBeanof Spring does, is named innanolog.caller.skip(org.springframework): its calls count for the application and are never reported.LOG.lock()after your ownLOG.init, ornanolog.logger.lock=truefor the logger of the configuration, makes laterLOG.initcalls 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.acmeforcom.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 whenLOGstarts or byLOG.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 itsSimpleDateFormat; 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.JsonLoggerwrites 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$1orcom.acme.Foo$1.sourceLength— abbreviates the fully qualified name as%logger{n}of Logback does: while it is longer thanncharacters, the segments of its package, from the left, are cut to their first letter. At 30com.acme.billing.payments.PaymentServicebecomesc.a.b.payments.PaymentService, at 20c.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 asLOG.dbgfinds the text of its arguments, and nothing is written when they are missing or newer than the classes.JsonLoggeradds"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.JsonLoggeralways writes the thread.showContext— the pairs ofLOG.context(...)after the message,requestId=r-17. On by default; since 1.4. See Context.stream— which levels go toSystem.err:err@ERROR(the default) sends only errors there,err@WARNwarnings and errors,erreverything,outnothing. 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;indentstarts 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;escapewrites them as\rand\n, so an entry and its stack trace are one physical line forgrepandtail. 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.JsonLoggerescapes its lines anyway. Since 1.4.color— when the level word is coloured: redERROR, yellowWARN, greenINFO, dimDEBUGandTRACE, magentaDBG.auto(the default) colours only a terminal and follows the NO_COLOR andFORCE_COLORconventions: no colours whenNO_COLORis set, colours whenFORCE_COLORis set to anything but0orfalse, otherwise only when standard output is a terminal andTERMis notdumb. A pipe, a file, the run log andJsonLoggernever get escape codes. On Windowsautodoes not colour withoutFORCE_COLOR: the console shows the codes as text unless the program turns their processing on, which Java does not do.alwaysandneverignore the environment; agent mode usesnever. 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;collapsewrites 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, sotail -fstill shows it. Only the console collapses: the run log,JsonLoggerandMemoryLoggerget every entry, and the run summary counts them all. Agent mode usescollapse; since 1.4.exceptionExclude/exceptionMaxFrames— shorter stack traces, see Shorter stack traces.traceEnabled…errorEnabled— per-level switches; everything is enabled by default, so switchTRACEandDEBUGoff in production, in code or withnanolog.level=INFO. Disabled levels are rejected before theLogEntryis 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
DEBUGon 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.paydoes not covercom.acme.payments. nanolog.level.<name>beats an item for the same name innanolog.levels.- Setters called after the constructor override the values it read, so
new ConsoleLogger().setDebugEnabled(false)in code wins overnanolog.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=allprints every one, including each failure of a logger, andoffnone, whileILogger.onDiagnosticstill gets the findings of strict mode and ofnanolog.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 toSystem.errand 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.propertiesis read whenLOGinitialises, so aConsoleLoggercreated before that sees only-Dand 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 thetryblock 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()readsnanolog.level,nanolog.levelsandnanolog.level.<name>again: from-Dand the environment as they are now, fromnanolog.propertiesas it was loaded at startup. It undoes every change made at run time, the level setters ofConsoleLoggerincluded; the display options stay as they are.CompositeLoggerpasses each change to those of its delegates that support it. The other loggers have no levels to change:Slf4jLoggertakes them from the SLF4J backend, andMemoryLoggercaptures 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:
TRACEtoOFF, 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
nullor blank name and anullor unknown level print a[NANOLOG]diagnostic and change nothing. - The same methods exist on
ConsoleLogger, and so onJsonLoggerandFileLogger, and onCompositeLogger. A custom logger supportsLOG.setLevel(...)by implementingILevelControl.
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
excludelists package or class prefixes. A run of two or more consecutive frames that match becomes one... N frames excludedline; 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.junitcoversorg.junit.runners.ParentRunner, notorg.junitx.maxFramesprints 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 whatprintStackTraceprints. A trace that cannot be shortened, because the throwable breaks while it is read, is printed the usual way. - In code:
setExceptionExclude("org.junit", ...)andsetExceptionMaxFrames(40)onConsoleLoggerandJsonLogger.Slf4jLoggeris 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 ofLOG.tag(...), when there is one),message(the formatted message).templateandargs— the raw message and the arguments as strings, for parameterized messages only; equal events can be grouped whatever their arguments.dbg,breadcrumb—truefor an entry ofLOG.dbgand for one held back bynanolog.buffer, see Breadcrumbs.fields— the arguments ofLOG.kv(...)as a nested object, when there are any;argsleaves out those that no{}takes. Select on them withjq 'select(.fields.orderId=="A-17")'; see Fields.context— the pairs ofLOG.context(...)as a nested object, when there are any. Numbers and booleans keep their JSON type, sojqcompares them as numbers:jq 'select(.context.attempt > 1)'.caller— the call site, when the source class was detected, with itssourceline undershowSourceLine;exception—class,messageandstackTrace, 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.
JsonLoggerextendsConsoleLogger: the same levels, the same level properties and the same streams (ERRORtoSystem.errby default). The display options do not apply.- In a pipe only standard output reaches the next program, so
java -jar app.jar | jqwould lose everyERRORentry.-Dnanolog.console.stream=outwrites 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=falseempties it then. Withoutnanolog.fileit isnanolog.login the working directory. - Each entry is written through at once, so a crash loses nothing that was logged.
nanolog.file.flush=bufferkeeps entries in memory untilLOG.flush(), a full buffer of 8 KB or the exit of the JVM, for a program that logs a lot. nanolog.file.maxSizerolls the file over:app.logbecomesapp.log.1, the older files move one up, and the oldest beyondnanolog.file.backupsis deleted. There is no rolling by date, no compression and no asynchronous writing.- The lines have the layout of
ConsoleLoggerand follow its settings, levels included;nanolog.file.format=jsonwrites the lines ofJsonLoggerinstead. 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 toSystem.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 setterssetAppend,setMaxSize,setBackups,setFlushandsetFormatchange the settings, andclose()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-apiis aprovideddependency 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,%methodand%class(Logback) or%l(Log4j 2) therefore show the code that calledLOG, notSlf4jLogger, 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)andrun(...)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: theLOG.timeorLOG.unitcall is no longer on the stack, and SLF4J has no way to pass a call site. A unit written asinterruptedat the end of the run shows a frame of Nanolog.ConsoleLogger,JsonLoggerand the run log show theLOG.timeorLOG.unitcall in every case. - In agent mode
LOG.dbgprints whatever the levels: aLOG.dbgline whose class hasDEBUGoff in the backend, the root atINFOas in Spring Boot, is printed by Nanolog onSystem.outin the format of its agent console, instead of being passed to a backend that would drop it. WithDEBUGon, 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 ofLOG.kv(...)that no{}takes are appended to the text askey=value, asConsoleLoggerwrites them; the key-value pairs of SLF4J 2 are not used, since backends treat them differently. The tag ofLOG.tag(...)is passed as an SLF4JMarkerof that name, so%markerof 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 throughorg.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
ROOTlogger. - Loggers are cached per source class in a
ConcurrentHashMapand never evicted, so with dynamic class reloading the cache retainsClassreferences.
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), andLOG.isDebugEnabled()asks it.TRACE,DEBUG,INFO,WARNandERRORbecomeFINEST,FINE,INFO,WARNINGandSEVERE, soLOG.dbgis aFINErecord. In agent mode aLOG.dbgline that JUL would drop is printed by Nanolog onSystem.outinstead, as withSlf4jLogger. - The message arrives formatted, followed by the fields of
LOG.kvand the context askey=value, since JUL has no place for them; the record names the call site as its source class and method, which%2$sofSimpleFormatterprints. - 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 ofLOGand 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 throwAssertionErrorwithout 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;assertTemplateLoggedmatches the message before its arguments were substituted.new MemoryLogger(capacity)keeps only the newest entries.LOG.initandinstall()are JVM-wide, so tests that install a logger must not run in parallel with each other. For parallel tests usecapture(), 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 ofnanolog.dbg=failon this thread go to the capture too, forassertNoDiagnostics(). - Only the current thread is captured: entries that the code under test logs from a thread pool reach the logger of
LOG. Captures nest, andclose()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@BeforeEachmethods to the@AfterEachones. 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
@BeforeAlland@AfterAllmethods, and the creation of each test instance, whereSpringExtensionstarts 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@BeforeAllmethod 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
MemoryLoggeror opensMemoryLogger.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) ornone. Withjunit.jupiter.extensions.autodetection.enabled=trueinjunit-platform.propertiesJUnit 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
Throwablein 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. InLOG.error("Cause: {}", e)the placeholder takes the exception, so onlye.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 withArrays.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
Supplierthrows, 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 thetemplateandargsofJsonLoggerand forassertTemplateLogged, and noisDebugEnabled()check is needed. A supplier that throws gives[FAILED supplier: <exception>]in place of the value. There are no overloads that take aSupplierfor 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 guardedtoString(). - With
nanolog.dump=auto(NANOLOG_DUMP=auto) an argument whose class has notoString()of its own is printed field by field, as inLOG.dbg:LOG.info("Added {}", line)printsAdded Line{sku="A-1", qty=2}instead ofAdded Line@1e643faf. Collections, maps, arrays andOptionalare walked, so a list of such objects is printed the same way. Everything with atoString()of its own, strings included, prints as before, without quotes, limits or redaction. The setting is off by default because it changes existing output;JsonLoggerputs the result intomessageandargsas 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:ConsoleLoggerandSlf4jLoggerappend it askey=value, quoted like the pairs of the context, and strict mode does not report it. JsonLoggerwrites every field into"fields", whether a{}took it or not; numbers and booleans stay JSON numbers and booleans. Any logger reads them fromLogEntry.getFields(), and those the message does not show fromgetTrailingFields().- 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 thatgetMessage()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 thetemplateofJsonLoggerandassertTemplateLoggedsee 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 asLOG.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.CompositeLoggerpasses 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=failreportsLOG.dbgcalls 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) ishide,truncate:<characters>orshow, andnanolog.content.<package or class>sets it for one package or class, the most specific rule winning, as with levels:-Dnanolog.content.com.acme.llm=showshows the prompts of one package while you debug. Rules for packages are system properties or keys ofnanolog.properties.- Escaped. In the text that reaches the log, line breaks and control characters are escaped,
\nand\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 itstoString()changes nothing. A payload in aLOG.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"};messageandargshold 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 bysk-***,AKIA***,Bearer ***andeyJ***. 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.secretkeeps no value and never formats it, so itstoString()is not called; every logger writes***, in the message, inargsandfieldsofJsonLogger, in the MDC ofSlf4jLoggerand in the assertion messages ofMemoryLogger.- A field of
LOG.kv(...)or a value ofLOG.context(...)is masked when its key, or a word of it, is innanolog.redact(NANOLOG_REDACT): by defaultpassword,passwd,secret,token,apikey,credentialandauthorization. Words are split at separators and at camel case, sopasswordcoversdb.passwordanduserPassword, andtokencoversX-Auth-Tokenbut notinput_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.contenthave 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 asparent, their warnings and errors count in it, andLOG.wrapcarries 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. Withnanolog.buffer=DEBUGthe 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_AIandSTOP, not the lower-case values of OpenTelemetry. WithJsonLoggerthe fields are typed:jqsums.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
}
ConsoleLoggerprints 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=falsehides them.JsonLoggerwrites a nested object,"context":{"requestId":"r-17"}, which cannot collide withlevel,messageand the other fields; numbers and booleans keep their JSON type.Slf4jLoggerputs 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(), soMemoryLoggerassertions and custom loggers see it, and the assertion messages ofMemoryLoggershow 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 ofLOG.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 aCallableto the compiler; write() -> { list.add(item); }where aRunnableis 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
nullor an empty map; anullkey 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:ConsoleLoggerprintstraceId=4bf92f35...after the message,JsonLoggerwrites them into"context",Slf4jLoggerputs 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.TraceIdProvidernames a class that implementsSupplier<Map<String, ?>>and has a public no-argument constructor; several are separated by commas and come before the providers ofaddContextProvider. 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 ofLOG.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:
ConsoleLoggerprints[skipped 241]after the message,JsonLoggerwrites"skipped":241,Slf4jLoggerappends[skipped 241]to the message, and any logger readsLogEntry.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()andatMostEvery(...)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 belowWARNare dropped wherever they come from, and the SQL entries atDEBUGare written even undernanolog.level=INFO. A tag without a rule follows the level of its class.resetLevels()reads the rules again;LOG.setLeveldoes not change them. ConsoleLoggerwrites[audit]after the source class,JsonLogger"tags":["audit"], andSlf4jLoggerpasses an SLF4JMarkernamed after the tag. Any logger readsLogEntry.getTags()and may answerILogger.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=DEBUGunderINFO, 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.catchingis 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
ERRORwith its stack trace, from the class and call site of theLOG.catchingcall, and the levels apply as usual. The actions may throw checked exceptions (LOG.ThrowingRunnable,LOG.ThrowingSupplier). AnErroris not caught, and anInterruptedExceptionis caught with the interrupt flag of the thread set again. Inside a unit a caught exception makes the unit fail, like anyERROR. - Threads.
LOG.installUncaughtExceptionHandler()installs a default handler that logsUncaught exception in thread worker-1with 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.outbecomes anINFOentry, a line ofSystem.erranERRORentry; 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 ofPrintStream,printfandprintStackTraceare skipped. - A line ends at
\nor\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.outwhile 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.SEVEREbecomesERROR,WARNINGWARN,INFOINFO,CONFIGandFINEDEBUG,FINERandFINESTTRACE; then the levels of Nanolog apply.- JUL decides first: a record below the level of its JUL logger,
INFOby default, never reaches Nanolog. To see theFINErecords 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 modulejava.loggingis present. Nanolog registers noSystem.LoggerFinderof its own, which would take overSystem.Loggerin 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+ aStackWalker 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 isnullwhen 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 becomeStackTraceElements (JavaLangAccess.getStackTraceElement); where the two disagree, underMethod.invoke, the call falls back to the stack trace of aThrowable. Where neither is available (another JVM, a native image without the metadata forStackWalker), the frames of aThrowablecarry only class names: they are resolved through the context class loader of the thread first and the class loader ofLOGsecond, 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 asNoClassDefFoundError, orMissingReflectionRegistrationErrorfrom GraalVM in a native image. - The stack is walked only for a level the logger may have enabled:
LOGfirst asksILogger.mayBeEnabled(level), so a level that is off for every class, such asDEBUGundernanolog.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
ILoggeris skipped, so a custom logger that logs throughLOGmust 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 anILoggerclass, or on Java 8 when the JVM records no stack traces (-XX:-StackTraceInThrowable).Slf4jLoggersends such entries to theROOTlogger.
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.logdoes not covercom.acme.logging. A nested class alone is written with$,com.acme.Outer$Helper. - A library that wraps
LOGcannot rely on the settings of the application: it callsLOG.skipCaller(Helper.class)once, for example in a static initializer. These classes are added to those named in the setting and stay skipped afterLOG.init(). Slf4jLoggerpasses the helper to a location-aware backend as the caller boundary, so%file:%lineof Logback and%lof 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,WARNorERROR.getSourceClass()— the detected or explicitly passed class;nullonly ifnullwas passed.getCaller()— theStackTraceElementof the logging call;nullwhen the source class was passed explicitly.getThrowable()— the exception ornull.getMessage()— the raw message object, already resolved from itsSupplier.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 fromLOG.dbg, and whethernanolog.bufferheld it back.getFields(),getTrailingFields()— the arguments ofLOG.kv(...)by name, and those of them that no{}took.getContext()— the pairs ofLOG.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
LOGmethods are safe to call from any thread as long as the installedILoggeris;ConsoleLoggerandSlf4jLoggerare. - A logger installed with
LOG.init(...)orMemoryLogger.install()is used by every thread from its next logging call, threads that are already running included. Levels may change at any time, throughLOG.setLevel(...)and the other level methods or the level setters ofConsoleLogger. The display setters (setShowDate,setDateFormatand the others) are meant for startup, not for concurrent reconfiguration. - A call at a level that is off for every class costs one
mayBeEnabledcheck, or oneisEnabledcheck 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 anisEnabledcheck even where the level is off, so a single rule such asnanolog.level.com.acme.db=TRACEmakes everytracecall without a class walk the stack. Message formatting andSupplierevaluation 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 throughConsoleLoggertakes 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.
¹ 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.
²⁶ 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.
FileLoggerof 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-characterAI_AGENTmade 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 linesand... and 1 more kindstook 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 withLOG.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 whenLOGinitialised 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.logkeeps the run before.LOG.init()stops the run log when its settings no longer turn it on, so a tool can setnanolog.agent=offand callLOG.init()before it logs. Before, such a run added two lines of about 600 characters and an emptylatest.log. - Logged text cannot make a line read other than it holds:
nanolog.console.multiline=escapeandindent, the console of agent mode included, the payloads ofLOG.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.logescapes asescapedoes, 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 oftail -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
BootstrapMethodErrorfrom the threadnanolog-summary, and the summary was lost. ALOG.unitstill 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()afternanolog.agent=off: one[NANOLOG]line on the console and last inlatest.logandlatest.errors.lognames 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 fornanolog.run=offandnanolog.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
forkCountabove 1: a Surefire fork that runs several test classes prints one summary after the last of them, through the newSummarySessionListener(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 withSlf4jLoggerfor one, orMemoryLogger.install()gets the run log added, andLOG.getLogger()returns aCompositeLoggerof both. A decorator that passes each entry on to the loggerLOG.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.inittojdk.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 innanolog.caller.skip, such asorg.springframeworkforMethodInvokingBean, 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 printsUnknown settingwhen it is set on the command line, where Surefire passes it to the JVMs of the tests as a system property.NANOLOG_VERSIONis 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 withforkCountabove 1 orreuseForks=falseeach fork points to the file with its own entries for the whole run. Before, every fork pointed tolatest.log, which held only the fork that started last. Elsewhere a run nameslatest.logwhile 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 thatNanologExtensionholds back are still counted, since the run log gets them when the test ends. NanologExtensionalso holds back the log of the class outside its tests: the@BeforeAlland@AfterAllmethods and the creation of the test instances, whereSpringExtensionstarts 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.lognext to the run log, withlatest.summary.log, one line each, ordered by level and call site so thatdiffcompares 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 ofLOG.timed(...)and ofLOG.unit(name, body)has the call site of that call in the%file:%lineof Logback and the%lof Log4j 2. Before, the backend named a frame of Nanolog,Timers.runorLOG.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,JsonLoggerand the run log show theLOG.timeorLOG.unitcall.- The run log no longer changes the levels of a logger the application installs:
LOG.isXxxEnabledand the lazy arguments of a call answer for that logger,Slf4jLoggerfor 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 afterLOG.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), withLOG.unit(level, name, body), writes the line of a failed or interrupted unit at another level thanERROR, such asWARNfor a job that is retried, where everyERRORwould raise an alert.okstaysINFO; the outcome, the counts and theerror.*fields do not change.- Agent mode with
Slf4jLoggerorJulLogger: aLOG.dbgline whose class hasDEBUGoff in the backend, the root atINFOas in Spring Boot, is printed by Nanolog onSystem.outin the format of the agent console. Before, the backend dropped it, and only the run log and the list ofLOG.dbgcalls 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 showsWARNand above, one line per entry, without dates or colours and with short stack traces,LOG.dbgprints whatever the levels, the run log is on, and one[NANOLOG]line says so and names the file.nanolog.agent=auto|on|offdecides; 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, theLOG.dbgcalls 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 runsSummaryListener, which the JUnit Platform loads by itself, prints it and the list ofLOG.dbgcalls when the tests have run, because Surefire drops what a shutdown hook of its forked JVM prints. - Run log for agents: with
nanolog.run=onevery entry of the run also goes totarget/nanolog/latest.log(Gradle:build/nanolog, otherwise.nanolog), warnings and errors tolatest.errors.logone line each, and the absolute path is printed whenLOGinitialises. Each run writesruns/<time>-<pid>.log,latest.logis 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.ConsoleLoggermarks the lineDBG,JsonLoggeradds"dbg":true,LogEntry.isDbg()tells the entry apart;nanolog.sourcesnames the source directories.- Objects whose class has no
toString()of its own are printed field by field instead ofInvoice@2f92e0f4: always inLOG.dbg, and in{}arguments withnanolog.dump=auto. Classes of the JDK are never reflected into, so nothing needs--add-openson 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.dbgcalls: when the JVM exits, one[NANOLOG]line lists the call sites that printed;nanolog.dbg=offsilences the calls,nanolog.dbg=failreports each one as a diagnostic that failsMemoryLogger.assertNoDiagnostics();NanologChecks.assertNoDbgCalls("src/main/java")fails a test while the sources callLOG.dbg, with the file, line and code of each call.MemoryLogger.assertNoDiagnostics()now saysNanolog reportedinstead ofstrict 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 ofput(...), the counts of warnings and errors logged inside it and, for a failed unit,error.type,error.messageand anerror.keythat stays the same between runs. Units nest (parent=), cross executors withLOG.wrapand are written asinterruptedwhen the run ends while they are open;nanolog.unit.sample/nanolog.unit.slowMssample the fast successful ones;run(...)andLOG.unit(name, body)record a thrown exception. - Settings that Nanolog does not know are reported when
LOGinitialises instead of being ignored: a mistypednanolog.*system property,NANOLOG_*environment variable or key ofnanolog.propertiesprints[NANOLOG] Unknown setting "nanolog.levle" (system property); did you mean "nanolog.level"?, a key of the file without thenanolog.prefix is reported as ignored, andNANOLOG_LEVEL_COM_ACMEpoints toNANOLOG_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, andnanolog.junit.output=failed|all|nonedecides what is printed.nanolog.console.multiline(setMultiline) forConsoleLogger:indentstarts every line of an entry after the first with a tab, so a message cannot forge an entry;escapewrites line breaks as\rand\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 usesescape.- Coloured level words on a terminal,
nanolog.console.color=auto|always|never(setColor): redERROR, yellowWARN, greenINFO, dimDEBUGandTRACE, magentaDBG.auto, the default, colours only when standard output is a terminal, honoursNO_COLOR,FORCE_COLORandTERM=dumb, and stays off on Windows and in agent mode; pipes, files, the run log andJsonLoggernever get escape codes. java.util.loggingboth 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()orhandlers=com.nanolaba.logging.NanologHandlerturns the records of JUL, and so ofSystem.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.FileLoggerwithnanolog.file=logs/app.logappends the entries to a file, in the text format ofConsoleLoggeror the JSON lines ofJsonLogger. Each entry is written through at once, or withnanolog.file.flush=bufferkept untilLOG.flush(); the file rolls over atnanolog.file.maxSize, withnanolog.file.backups.LOG.flush()andILogger.flush()are new.- A real module descriptor: on Java 9+ the jar is the module
com.nanolaba.nanolog, fromMETA-INF/versions/9/module-info.classof a multi-release jar, sojlinkaccepts it; the module needs onlyjava.base. LOG.captureSystemStreams()andnanolog.captureSystemStreams=trueturn the lines printed toSystem.outandSystem.errintoINFOandERRORentries 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
LOGin every form from Kotlin, so an overload that is ambiguous for Kotlin, as in tinylog, fails the build. Slf4jLoggeris 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()andnanolog.logger.lock=truekeep the installed logger and turn laterLOG.initcalls into no-ops with such a line;MemoryLogger.install()still works under the lock. - Documentation: a
nanolog.propertiesinsrc/test/resourcesreplaces the one insrc/main/resourcesin tests, as a whole file, not merged. - Several
nanolog.propertieson 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, andnanolog.tags=audit=WARN,sql=DEBUGsets levels per tag, which take precedence over the levels of the class.ConsoleLoggerwrites[audit],JsonLogger"tags":["audit"],Slf4jLoggerpasses an SLF4JMarker;LogEntry.getTags()andILogger.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,JsonLoggerandassertTemplateLogged. nanolog.console.sourceLength(setSourceLength) abbreviates a fully qualified source name like%logger{n}of Logback:com.acme.billing.payments.PaymentServicebecomesc.a.b.p.PaymentServiceat 20 characters.nanolog.console.timeZone(setTimeZone) sets the time zone of theConsoleLoggertimestamps, such asUTCorEurope/Berlin; an unknown ID is reported instead of being taken for GMT.nanolog.console.dateFormat=isostands for the ISO 8601 pattern with milliseconds and the offset of the zone.- Context providers:
LOG.addContextProvider(() -> ids)andnanolog.context.provider=com.acme.TraceIdProvideradd the keys of a context of their own, such as the trace ID of OpenTelemetry, to every entry, after the pairs ofLOG.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.loggingandLOG.skipCaller(Helper.class)skip the frames of classes and packages that log for others, so an entry logged throughAudit.record(...)gets the source class, call site and rate limit of the code that called the helper, andSlf4jLoggerpasses 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 asLOG.info("User " + id + " from {}", ip). Like the placeholder check, both reachILogger.onDiagnosticand failMemoryLogger.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.getCallerClassgives 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 aThrowablestays 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,apikeyand the others ofnanolog.redact, are masked when the entry is created; a shownLOG.contentmasks keys of model providers, AWS keys, bearer tokens and JSON web tokens. LOG.time("Load users")andLOG.timed("Count users", () -> ...)time a block:Load users took 123 mswith the fieldstimerandduration_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,JsonLoggerandMemoryLoggerkeep 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 aConsoleLoggercreated again does not repeat them;allprints every one,offnone. 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 asLOG.dbgfinds its source and left out when the source is missing or stale;JsonLoggeradds"source"to"caller". A part of aConsoleLoggerline that follows a line break no longer starts with a space.LOG.catching(() -> cleanup())logs an exception atERRORwith its stack trace and carries on,LOG.catching(() -> parse(s), -1)returns a default instead; checked exceptions are allowed, anErroris 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 asLOG.content, and a transcript atDEBUG. - 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, unlessnanolog.content=truncate:<characters>orshowsays otherwise, for all classes or, throughnanolog.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=DEBUGholdsDEBUGandTRACEentries back, the newest 200 per thread (nanolog.buffer.size), and writes them before the nextERRORunder--- 37 earlier DEBUG entries ---; insideLOG.unitthe 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, andJsonLoggermarks them"breadcrumb":true. - Fields:
LOG.kv("orderId", id)names an argument. In a{}it prints its value; without oneConsoleLoggerandSlf4jLoggerappendorderId=A-17to the message and strict mode does not count it.JsonLoggerwrites every field into a"fields"object whose numbers and booleans keep their type, sojqselects entries by them, andLogEntry.getFields()gives them to any logger. - Context:
try (LOG.Context c = LOG.context("requestId", id)) { ... }addsrequestId=r-17to every entry the thread logs inside the block, nested scopes put the previous value back, andLOG.wrap(task)carries the context into a task that another thread runs.ConsoleLoggerprints the pairs after the message (nanolog.console.showContext),JsonLoggerwrites a"context"object whose numbers and booleans keep their type,Slf4jLoggerputs the pairs into the MDC for%X{requestId}, andLogEntry.getContext()gives them to any logger. MemoryLogger.capture()andcaptureForwarding()capture the entries of the current thread only, every level, while the logger ofLOGstays 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(), andLOG.withLevel(name, level)for atryblock. The level is aLogEntryLevelor a string such as"OFF", as in the settings.ConsoleLogger,JsonLoggerandCompositeLoggerimplement the newILevelControl, and the level setters ofConsoleLoggermay now be called while other threads log. LOG.once()andLOG.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(), whichConsoleLogger,JsonLoggerandSlf4jLoggerprint.- Shorter stack traces in
ConsoleLoggerandJsonLogger:nanolog.exception.excludecollapses runs of frames from packages such asorg.junitorjdk.internal.reflectinto... N frames excluded,nanolog.exception.maxFramescaps the frames of each throwable. Without them the output is that ofprintStackTrace, as before. MemoryLogger:assertNoneAtOrAbove(level),assertLogged(level, text)andassertTemplateLogged(level, template)fail with anAssertionErrorthat 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, andMemoryLogger.assertNoDiagnostics()fails on them.CompositeLoggerforwards them. ConsoleLogger,JsonLogger:nanolog.console.stream(orsetStream) chooses the stream of each level:outsends everything to standard output, sojava -jar app.jar | jqkeeps theERRORlines,errsends everything to standard error,err@WARNwarnings and errors. The defaulterr@ERRORis the former behaviour.ConsoleLogger:setShowThread(true)ornanolog.console.showThread=trueprints 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:
LOGasks the newILogger.mayBeEnabled(level)first.ConsoleLogger,JsonLoggerandCompositeLoggeranswer it from their switches, package rules and delegates; other loggers keep the defaulttrueand 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 theThrowablewalk. - 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 toSystem.errinstead. InsideCompositeLoggera throwing delegate no longer stops the others. - A lazy message whose
Supplierthrows 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 anILogger), the entry is logged without a source class instead of throwingIllegalStateException. - Caller detection no longer lets an error from a class loader escape: a frame whose class fails to load with
NoClassDefFoundError,MissingReflectionRegistrationErrorfrom GraalVM or any other throwable is resolved through the other loader or skipped. - A logger installed with
LOG.init(...)orMemoryLogger.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 toLOG.setLevelfrom a request, an exception message or a template, are printed as\u000aescapes, so such a value cannot forge a line of the log. - Documentation: the
Slf4jLoggersection no longer says that MDC works with every backend; slf4j-simple and slf4j-nop discard MDC values. - Documentation:
ILogger.isEnabledno longer promises that returningfalseskips the whole cost of a call; caller detection has already walked the stack by then. - JMH benchmarks in
src/jmh, built withmvn -P benchmark test-compile exec:exec, with results for JDK 8 to 25 insrc/jmh/RESULTS.md; the README quotes the measured costs.
1.2
- A trailing
Throwablethat no{}consumes becomes the exception of the entry, as in SLF4J:LOG.error("Failed", e)andLOG.error("Failed {}", id, e)no longer drop the stack trace. LogEntry.getCaller()returns the frame of the logging call, andConsoleLogger.setShowLocation(true)prints it as[PaymentService.charge(PaymentService.java:87)].ConsoleLoggerreads its levels and options from properties and environment variables:nanolog.level,nanolog.level.<package or class>,nanolog.levelsandnanolog.console.*. Every property,nanolog.loggerandnanolog.configincluded, can be set as an environment variable (NANOLOG_LEVEL), which beatsnanolog.properties.JsonLoggerwrites one JSON object per line.LogEntry.getTimestamp()andLogEntry.getThreadName()tell when and where an entry was created.MemoryLoggercaptures entries in tests (try (MemoryLogger log = MemoryLogger.install()) { ... }),CompositeLoggersends entries to several loggers.nanolog.strict=truereports 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 calledLOGin%file:%lineand%l, instead ofSlf4jLogger.log.ConsoleLogger: a throwable whosetoString()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.txtand the agent skillskills/nanolog/SKILL.mdgive coding agents the rules of the library; both are generated with the README.
1.1
- New overloads
LOG.info(throwable, "... {} ...", args)andLOG.info(sourceClass, throwable, "... {} ...", args)for every level: an exception together with a parameterized message. nanolog.properties: onlynanolog.keys are copied into system properties; other keys are ignored.Slf4jLogger: anullsource class goes to theROOTlogger instead of throwing; an entry without a message no longer logs the wordnull.- 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 anObject[]argument no longer propagates to the caller. - A
nullcontext 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
- Questions and feedback: Discussions · bugs: Issues · English or Russian; what to include is in SUPPORT.md.
- Building, testing and changing the code or the docs: see CONTRIBUTING.md.
- Vulnerabilities are reported privately: see SECURITY.md.
License
Generated with nanolaba/readme-generator
Reviews (0)
Sign in to leave a review.
Leave a reviewNo results found