Skip to main content

Log4j2 Logging Levels Explained: Configuration, Custom Levels and Changing Levels at Runtime

How Log4j2 logging levels really work in Spring Boot 4.1: the threshold rule as a matrix, level inheritance, the additivity trap that prints lines twice, custom DIAG and PERF levels, changing levels at runtime through Actuator (and what it refuses), and what a disabled log call still costs. Every claim comes from a real run in the companion repository.

Your log is either a firehose or a desert. The one line you need during an incident is buried under ten thousand routine status messages, or it was never written because somebody set the threshold too high. Logging levels are the control that decides which of those two you get, and they are one of the few things you can change without touching the code. This guide builds a small Spring Boot 4 application on Log4j2, and every claim in it comes from running that application. You will learn what a level really is, how a logger gets its level, why a line sometimes prints twice, how to add levels of your own, how to change a level while the application is running, and what a log call that is switched off still costs you. The whole project is in the log4j2-levels module of the spring-boot-demo repository; each section below links the exact file or captured output it relies on.
Versions this article was run against. Spring Boot 4.1.2 (the newest GA on maven-metadata.xml), Log4j2 2.25.5 (the version Spring Boot 4.1.2 manages; Maven Central also lists 2.26.1), Temurin JDK 25.0.5. Logback 1.5.38 appears only in the deliberately broken build in the last third. Everything below is regenerated by one command, ./scripts/run-all.sh.

What changed from the first version of this article. Three things in it were wrong or incomplete when I ran them: the XML and properties examples gave a logger its own appender without turning additivity off, so every line printed twice; the properties example referred to a Console appender it never declared; and the “good” parameterized example called user.toString() eagerly, so it did the work it claimed to avoid. All three are corrected below, with the output that shows them.

A level is just a number, and a logger lets through everything at or below its threshold

Every log statement you write carries a level: FATAL, ERROR, WARN, INFO, DEBUG or TRACE. Every logger also has a threshold, which is itself a level. When a statement runs, Log4j2 compares the two and either hands the event to the appenders or throws it away. That is the whole mechanism, and the same compiled code can be chatty on a laptop and quiet in production simply because the threshold differs. The comparison is between integers. Each level has a number, and a smaller number means more severe. An event is printed when its number is at or below the logger’s threshold, which is why setting a logger to INFO also lets WARN, ERROR and FATAL through but not DEBUG or TRACE.
FATAL100ERROR200WARN300INFO400DEBUG500TRACE600logger threshold = INFO (400)printed: the event’s number is at or below the thresholddropped: higher number, more detailLower number = more severe. The logger compares two integers and nothing else.
The picture shows INFO as the threshold. Everything to the left of the dashed line, up to and including 400, is printed; DEBUG and TRACE sit to the right and are dropped. These are the eight built-in levels and their numbers, read from the log4j-api jar on the classpath (output file 01-standard-levels.txt):
LevelInt valueDescription
OFF0Turns off all logging. A complete silencer.
FATAL100Severe errors causing application termination. The “stop everything” signal.
ERROR200Error events that may allow the application to continue running.
WARN300Potentially harmful situations or “code smells” that warrant attention.
INFO400Informational messages highlighting the normal progress of the application.
DEBUG500Detailed debugging information, like variable states or parameters.
TRACE600The most detailed (and noisiest) information, like method entry/exit.
ALLInteger.MAX_VALUE (2147483647)Enables all logging levels.
To see the rule act rather than take it on trust, the test LevelsTest (LevelsTest.java) sets one logger to each threshold in turn, logs one event at every level, and records both what isEnabled answered and how many lines the real Console appender printed. The last column is the number of lines that actually appeared (output file 02-threshold-matrix.txt):
# rows: the logger's threshold. columns: the event's level. 'yes' = isEnabled(level).
# last column: lines the real Console appender printed when one event of each level was logged
threshold  FATAL ERROR WARN  INFO  DEBUG TRACE  printed
TRACE      yes   yes   yes   yes   yes   yes    6
DEBUG      yes   yes   yes   yes   yes   -      5
INFO       yes   yes   yes   yes   -     -      4
WARN       yes   yes   yes   -     -     -      3
ERROR      yes   yes   -     -     -     -      2
FATAL      yes   -     -     -     -     -      1
OFF        -     -     -     -     -     -      0
Read down the INFO row: FATAL, ERROR, WARN and INFO say yes, DEBUG and TRACE say no, and four lines were printed. The two edges are worth a look. A TRACE threshold prints all six, and OFF prints none, because OFF is 0 and even FATAL at 100 is above it.
OFF is a threshold, not a level you log at. The same transcript file records FATAL.isMoreSpecificThan(OFF) = false: with a threshold of OFF, nothing is more severe than the threshold, so nothing passes. This is why a logger set to OFF is silent even for FATAL.
Going deeper: the one comparison Log4j2 performs The method behind the rule is Level.isMoreSpecificThan, and the test prints it for a few pairs (output file 01-standard-levels.txt):
# the rule: an event is enabled when event.isMoreSpecificThan(threshold), i.e. its int is <= the threshold's
INFO.isMoreSpecificThan(DEBUG)  = true
DEBUG.isMoreSpecificThan(INFO)  = false
INFO.isMoreSpecificThan(INFO)   = true
FATAL.isMoreSpecificThan(OFF)   = false
TRACE.isMoreSpecificThan(ALL)   = true
“More specific” just means “has a number at or below”, and a level is more specific than itself, which is why an INFO event passes an INFO threshold. ALL is Integer.MAX_VALUE, so every level is more specific than it.
Going deeper

Getting Log4j2 into a Spring Boot 4 application takes one dependency swap and one file

Spring Boot uses Logback unless you tell it otherwise. Every starter depends on spring-boot-starter-logging, which brings Logback in, so switching to Log4j2 means excluding that artifact from each starter and adding spring-boot-starter-log4j2 (file pom.xml):
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-webmvc</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-logging</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
The first block is one starter and the second is the replacement, both taken straight from pom.xml; the same exclusion sits on all four starters the module uses. mvn dependency:tree confirms the result: Log4j2 only, no Logback (output file 12-dependency-tree.txt):
# mvn dependency:tree for the module (Log4j2 only)
  com.ankurm:log4j2-levels:jar:1.0.0
  \- org.springframework.boot:spring-boot-starter-log4j2:jar:4.1.2:compile
     +- org.apache.logging.log4j:log4j-slf4j2-impl:jar:2.25.5:compile
     |  +- org.apache.logging.log4j:log4j-api:jar:2.25.5:compile
     |  \- org.slf4j:slf4j-api:jar:2.0.20:compile
     +- org.apache.logging.log4j:log4j-core:jar:2.25.5:compile
     \- org.apache.logging.log4j:log4j-jul:jar:2.25.5:compile
Now the configuration file. Spring Boot looks for log4j2-spring.xml on the classpath, and the test in ConfigTest.java prints the file name Log4j2 was actually handed, so that is not an assumption. Here are the appender and the root logger (file log4j2-spring.xml):
    <Appenders>
        <!-- follow="true" makes the appender look up System.out on every write, which is what lets
             the tests swap System.out and read exactly what the real appender printed. -->
        <Console name="Console" target="SYSTEM_OUT" follow="true">
            <PatternLayout pattern="%-5level %logger{1.} - %msg%n%throwable{short}"/>
        </Console>
    </Appenders>

    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
        </Root>
The pattern %-5level %logger{1.} - %msg%n prints the level padded to five characters, the logger name with every package abbreviated to its first letter, and the message. A real deployment would add %d for a timestamp and %t for the thread; they are left out here so the captured output is the same on every run. The root logger is set to INFO, which is the default for every logger that has no entry of its own. Start the packaged jar and ask it to log one line at every level through a logger in the service package. The /demo/log endpoint (file LogController.java) answers with which levels were enabled, and the console shows what printed (output file 09-live-run.txt; ignore DIAG and PERF for now, they are section 5):
$ curl 'localhost:18091/demo/log?name=com.ankurm.log4j2levels.service.Probe'
{"FATAL":true,"ERROR":true,"WARN":true,"DIAG":true,"INFO":true,"PERF":true,"DEBUG":true,"TRACE":false} [HTTP 200]
FATAL c.a.l.s.Probe - demo line at FATAL
ERROR c.a.l.s.Probe - demo line at ERROR
WARN  c.a.l.s.Probe - demo line at WARN
DIAG  c.a.l.s.Probe - demo line at DIAG
INFO  c.a.l.s.Probe - demo line at INFO
PERF  c.a.l.s.Probe - demo line at PERF
DEBUG c.a.l.s.Probe - demo line at DEBUG
The exclusion has to be on every starter. If one starter keeps its path to spring-boot-starter-logging, Logback comes back alongside Log4j2 and your XML stops applying, without an error. Section 8 reproduces exactly that.
Going deeper: the same configuration as a .properties file Log4j2 also reads a properties format. The file below is the equivalent of the XML and, unlike the snippet in the first version of this article, it declares the Console appender that the loggers refer to (file log4j2-example.properties):
status = warn

appender.console.type = Console
appender.console.name = Console
appender.console.target = SYSTEM_OUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %-5level %logger{1.} - %msg%n

rootLogger.level = info
rootLogger.appenderRef.stdout.ref = Console

logger.service.name = com.ankurm.log4j2levels.service
logger.service.level = debug
logger.service.additivity = false
logger.service.appenderRef.stdout.ref = Console

logger.db.name = com.ankurm.log4j2levels.db
logger.db.level = error
A test loads it into a separate LoggerContext so the application’s own configuration is untouched, and prints what it gets (output file 13-properties-config.txt):
# loaded from log4j2-example.properties
logger                                           effective
com.ankurm.log4j2levels.service.UserService      DEBUG
com.ankurm.log4j2levels.db.UserRepository        ERROR
com.ankurm.log4j2levels.billing.InvoiceService   INFO
org.example.Unrelated                            INFO
service additivity = false
db additivity      = true
appenders: [Console]
Going deeper

A logger takes its level from the nearest ancestor that has one configured

Loggers are named, and names with dots form a tree: com.ankurm.log4j2levels.service.UserService is a child of com.ankurm.log4j2levels.service, which is a child of com.ankurm.log4j2levels, and so on up to the root. You rarely configure every logger. You configure a few packages and let the rest inherit.
rootconfigured: INFOserviceconfigured: DEBUGdbconfigured: ERRORbillingno entry: INFOdiagconfigured: DIAGdupconfigured: INFOservice.UserServiceinherits: DEBUGbilling.InvoiceServiceinherits: INFO (root)Solid boxes have an entry in log4j2-spring.xml. Dashed boxes have none, so they take the level of the nearest solid ancestor.
Solid boxes have an entry in the XML; dashed boxes do not. UserService has no entry, so it takes DEBUG from the service package. InvoiceService has no entry and neither does its package, so it climbs all the way to the root and gets INFO. The test ConfigTest (ConfigTest.java) asks Log4j2 for each logger’s effective level and for the name of the configuration that supplied it (output file 03-effective-levels.txt):
logger                                           effective level comes from
com.ankurm.log4j2levels.service.UserService      DEBUG     com.ankurm.log4j2levels.service
com.ankurm.log4j2levels.service.sub.Deeper       DEBUG     com.ankurm.log4j2levels.service
com.ankurm.log4j2levels.db.UserRepository        ERROR     com.ankurm.log4j2levels.db
com.ankurm.log4j2levels.billing.InvoiceService   INFO      root
org.example.Unrelated                            INFO      root
com.ankurm.log4j2levels.diag.Whatever            DIAG      com.ankurm.log4j2levels.diag
The last column is the useful one when a level surprises you: it names the entry that decided it. A package deeper in the tree than any entry, like service.sub.Deeper, still resolves to service. You can also set levels from code, which is mostly useful in tests. LevelsTest does it with Configurator.setLevel before every row of the matrix in section 1 (file LevelsTest.java):
            for (Level threshold : THRESHOLDS) {
                Configurator.setLevel("matrix.demo", threshold);
A configured level and an effective level are different things. Asking a logger for its level gives the effective one, which may have been inherited. When you want to know why, look for the entry that supplied it, not for a setting on the logger itself.
Going deeper

A logger with its own appender prints every line twice unless you turn additivity off

This is the mistake the first version of this article made in both of its configuration examples, and it is easy to make. A logger passes its events to its own appenders and then up to its parent’s appenders. That second step is called additivity and it is on by default. If you give a child logger an appender that points at the same Console the root already uses, the line is printed by both.
dup: appender of its own, additivity left at truelogger dupConsole (dup)line 1Console (root)line 2, passed up by additivityservice: appender of its own, additivity=”false”logger serviceConsole (service)line 1, and nothing elsenot passed on to the rootEvery logger hands its events to its parent as well, unless additivity is false. The root is where the second copy comes from.
The top row is the trap. The bottom row is the fix: additivity="false" stops the event after the logger’s own appender. A third arrangement, a logger with no appender at all, relies on the root’s through additivity and prints once. All three exist in the configuration (file log4j2-spring.xml):
        <!-- additivity="false" plus its own appender: lines are printed once. -->
        <Logger name="com.ankurm.log4j2levels.service" level="debug" additivity="false">
            <AppenderRef ref="Console"/>
        </Logger>
        <!-- No appender of its own: it uses the root's through additivity. -->
        <Logger name="com.ankurm.log4j2levels.db" level="error"/>
        <!-- The trap: an appender of its own AND additivity left at its default (true). -->
        <Logger name="com.ankurm.log4j2levels.dup" level="info">
            <AppenderRef ref="Console"/>
        </Logger>
One INFO event through each, counted from what the Console appender really printed (output file 04-additivity.txt):
# logger 'dup': <AppenderRef ref="Console"/> and additivity left at its default (true)
INFO  c.a.l.dup - order 7 shipped
INFO  c.a.l.dup - order 7 shipped
lines printed: 2

# logger 'service': <AppenderRef ref="Console"/> and additivity="false"
INFO  c.a.l.service - order 7 shipped
lines printed: 1
The fingerprint of this bug is a message that appears twice with identical text. If every line from one package is doubled and nothing else is, look in the configuration for a logger that lists an appender and does not say additivity="false". The first version of this article configured com.ankurm.db exactly like that.
Going deeper

Custom levels are names you attach to a number, and the number decides where they fit

If INFO feels too broad and DEBUG too noisy, you can define a level of your own. A custom level is only a name and an integer. The integer slots it into the same number line as the standard levels, and everything in sections 1 to 4 applies to it unchanged.
FATAL100ERROR200WARN300INFO400DEBUG500TRACE600DIAG350PERF450A threshold of INFO lets DIAG through (350 is at or below 400) and holds PERF back (450 is above it).The names are yours. The position comes only from the number you give them.
DIAG at 350 sits between WARN and INFO, so any logger that shows INFO also shows DIAG. PERF at 450 sits between INFO and DEBUG, so it appears only when DEBUG-ish detail is switched on. You declare them in the configuration (file log4j2-spring.xml):
    <CustomLevels>
        <CustomLevel name="DIAG" intLevel="350"/>
        <CustomLevel name="PERF" intLevel="450"/>
    </CustomLevels>
In code, Level.forName registers the level the first time and returns the existing one afterwards (file Levels.java):
    public static final Level DIAG = Level.forName("DIAG", 350);

    /** Sits between INFO (400) and DEBUG (500): hidden at INFO, shown at DEBUG. */
    public static final Level PERF = Level.forName("PERF", 450);
CustomLevelsTest (CustomLevelsTest.java) lists every registered level in order, then tries the lookups and each threshold (output file 06-custom-levels.txt):
# every registered level, most severe first (OFF and ALL left out)
FATAL 100
ERROR 200
WARN  300
DIAG  350
INFO  400
PERF  450
DEBUG 500
TRACE 600

# lookups
Level.getLevel("DIAG")        = DIAG
Level.getLevel("NOPE")        = null
Level.forName("DIAG", 999)    = DIAG (intLevel 350)
# which of DIAG and PERF are enabled at each threshold
threshold  DIAG  PERF 
WARN       -     -    
DIAG       yes   -    
INFO       yes   -    
PERF       yes   yes  
DEBUG      yes   yes  
The lower-case level="diag" from the first version of this article does work. A logger configured that way has DIAG as its threshold, so ERROR, WARN and DIAG pass and INFO, PERF and DEBUG do not, as the same transcript shows. Logging through the levels is one call each (file UserService.java), and the same two lines behave differently at two thresholds (output file 06-custom-levels.txt):
    public void diagnose() {
        // Custom levels, see Levels.java
        logger.log(com.ankurm.log4j2levels.Levels.DIAG, "cache size = 42");
        logger.log(com.ankurm.log4j2levels.Levels.PERF, "lookup took 3 ms");
    }
# UserService.diagnose() with the service package at DEBUG: both custom lines print
DIAG  c.a.l.s.UserService - cache size = 42
PERF  c.a.l.s.UserService - lookup took 3 ms
# and with it at INFO: only DIAG prints
DIAG  c.a.l.s.UserService - cache size = 42
Level.forName("DIAG", 999) does not redefine DIAG. The transcript shows it returning the existing level with intLevel 350. A second definition with a different number is silently ignored, so two files that disagree about a custom level’s number will not fail; one of them simply loses.
Going deeper: why the code uses forName and not getLevel The first version of this article fetched its levels with Level.getLevel("DIAG") into a static final field. That call only looks a name up. The transcript above shows Level.getLevel("NOPE") returning null for a name nobody has registered. Whether DIAG is registered at the moment your class initialises depends on whether the configuration has been read yet, and a field initialised too early would hold null and fail on the first log call. Level.forName registers the name if it is missing, so it does not depend on that order. I did not construct the failing order in the sandbox; the null for an unregistered name is what was measured.
Going deeper

You can change a level while the application runs, with some limits worth knowing

Restarting to turn DEBUG on is rarely what you want during an incident. Spring Boot Actuator has a loggers endpoint that reads and changes levels in a running process. It is not exposed by default; this module enables it in application.yml (file application.yml):
management:
  endpoints:
    web:
      exposure:
        include: loggers,health
ActuatorLoggersTest (ActuatorLoggersTest.java) drives it through MockMvc and the packaged jar drives it through real HTTP. First, reading a logger the XML configures and one that only inherits, then raising the package to TRACE and checking that a trace line really prints (output file 08-actuator-loggers.txt):
# 1. a logger the XML configures, and one that only inherits from it
GET  /actuator/loggers/com.ankurm.log4j2levels.service -> 200 {"configuredLevel":"DEBUG","effectiveLevel":"DEBUG"}
GET  /actuator/loggers/com.ankurm.log4j2levels.service.UserService -> 200 {"effectiveLevel":"DEBUG"}

# 2. raise the service package to TRACE and log a trace line through UserService's logger
POST /actuator/loggers/com.ankurm.log4j2levels.service {"configuredLevel":"TRACE"} -> 204 
GET  /actuator/loggers/com.ankurm.log4j2levels.service.UserService -> 200 {"effectiveLevel":"TRACE"}
printed: TRACE c.a.l.s.UserService - probe
Notice that the inheriting logger reports only an effectiveLevel, while the configured one reports both. The change is live immediately and applies to the whole subtree. The same thing from the packaged jar under Tomcat, with the change made by curl (output file 09-live-run.txt):
# raise billing to TRACE with Actuator, repeat the request
$ curl -X POST -H 'Content-Type: application/json' -d '{"configuredLevel":"TRACE"}' localhost:18091/actuator/loggers/com.ankurm.log4j2levels.billing
 [HTTP 204]
{"FATAL":true,"ERROR":true,"WARN":true,"DIAG":true,"INFO":true,"PERF":true,"DEBUG":true,"TRACE":true} [HTTP 200]
TRACE lines printed: 1
Where a level comes from matters once you have more than one source. There are three, and they are applied in this order.
1. log4j2-spring.xmlread when logging startsthen2. logging.level.* property or LOGGING_LEVEL_* variableapplied at startup, replaces what the file saidthen3. POST /actuator/loggers/{name}applied while the application runsTranscript 10: the property beat the file.Transcript 08: a POST changed it live.
The file is read first. A logging.level.* property or its environment-variable form is applied at startup and replaces what the file said. A POST to the endpoint is applied last, while the application runs. Transcript 10 starts the jar with each override (output file 10-property-overrides.txt):
# log4j2-spring.xml says: com.ankurm.log4j2levels.service = DEBUG, root = INFO

# 1. --logging.level.com.ankurm.log4j2levels.service=WARN on the command line
{"configuredLevel":"WARN","effectiveLevel":"WARN"} [HTTP 200]

# 2. the same override as an environment variable
{"configuredLevel":"TRACE","effectiveLevel":"TRACE"} [HTTP 200]
The root logger can be overridden the same way (same file, 10-property-overrides.txt):
# 3. --logging.level.root=ERROR, which the XML's root level should be competing with
{"effectiveLevel":"ERROR"} [HTTP 200]
The XML says the service package is DEBUG. The command-line property made it WARN, the environment variable made it TRACE, and logging.level.root=ERROR overrode the root’s INFO for a package that inherits from it. None of that edited the file. Now the limits.
Custom levels do not work through Actuator or logging.level.*. Posting "configuredLevel":"DIAG" to the endpoint returns 400. Worse, putting logging.level.com.ankurm.log4j2levels.service=DIAG in a property stops the application from starting at all. Spring Boot converts the value to its own LogLevel enum, which has seven values and no DIAG. Reading a DIAG logger through the endpoint works fine; setting one does not.
Here is the startup failure itself, as Spring Boot prints it (10-property-overrides.txt):
# 4. a custom level through the property: --logging.level.com.ankurm.log4j2levels.service=DIAG
app did not start; first lines of its output:
ERROR o.s.b.d.LoggingFailureAnalysisReporter - 
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to bind properties under 'logging.level.com.ankurm.log4j2levels.service' to org.springframework.boot.logging.LogLevel:
    Property: logging.level.com.ankurm.log4j2levels.service
    Value: "DIAG"
    Origin: "logging.level.com.ankurm.log4j2levels.service" from property source "commandLineArgs"
    Reason: failed to convert java.lang.String to org.springframework.boot.logging.LogLevel (caused by java.lang.IllegalArgumentException: No enum constant org.springframework.boot.logging.LogLevel.DIAG)
Action:
Update your application's configuration. The following values are valid:
    DEBUG
    ERROR
    FATAL
    INFO
    OFF
    TRACE
    WARN
Reset does not go back to the XML. Posting "configuredLevel":null to the service package, which the XML sets to DEBUG, left it at INFO, the root’s level, and the DEBUG line after the reset printed nothing. Reset in this setup means “remove the override and inherit”, not “restore the file”. If you want DEBUG back, post DEBUG.
# 3. reset it with configuredLevel null
POST /actuator/loggers/com.ankurm.log4j2levels.service {"configuredLevel":null} -> 204 
GET  /actuator/loggers/com.ankurm.log4j2levels.service -> 200 {"configuredLevel":"INFO","effectiveLevel":"INFO"}
GET  /actuator/loggers/com.ankurm.log4j2levels.service.UserService -> 200 {"effectiveLevel":"INFO"}
a debug line after the reset printed: nothing
Two smaller observations from the same transcript, both measured and neither explained by me. A lower-case "debug" was accepted with 204, while "LOUD" got 400. And GET /actuator/loggers/ROOT returned 404 over real HTTP as well as in MockMvc, even though a POST to ROOT worked and changed every inheriting logger, and the full listing does contain a ROOT entry (output file 08-actuator-loggers.txt). I did not inspect why.
# 6. the root logger
GET  /actuator/loggers/ROOT -> 404 
POST /actuator/loggers/ROOT {"configuredLevel":"WARN"} -> 204 
GET  /actuator/loggers/com.ankurm.log4j2levels.billing.InvoiceService -> 200 {"effectiveLevel":"WARN"}
POST /actuator/loggers/ROOT {"configuredLevel":"INFO"} -> 204 
GET  /actuator/loggers/ROOT -> 404 

# 7. the full listing: the levels it offers, and how the root logger is named
GET  /actuator/loggers -> "levels":["OFF","FATAL","ERROR","WARN","INFO","DEBUG","TRACE"]
     entry: "ROOT":{"effectiveLevel":"INFO"}
     lists com.ankurm.log4j2levels.service: true
Going deeper

A disabled log call can still do the work you were trying to avoid

A DEBUG statement in production does not print, but that does not mean it costs nothing. Java evaluates the arguments before the call, so anything expensive you pass in is computed whether or not the level is on. This is the most common avoidable logging cost, and the first version of this article got the advice half right. The test ArgumentEvaluationTest (ArgumentEvaluationTest.java) counts how many times toString() runs for six ways of writing the same DEBUG statement, once with DEBUG off and once with it on (output file 07-argument-evaluation.txt):
# times user.toString() ran for one call, threshold INFO (debug off) vs DEBUG (debug on)
call                                             debug off  debug on
debug("User: " + user)                           1          1
debug("User: {}", user)                          0          1
debug("User: {}", user.toString())               1          1
debug(() -> "User: " + user)                     0          1
debug("User: {}", () -> user.toString())         0          1
if (isDebugEnabled()) debug("User: " + user)     0          1
The rows tell three different stories. Concatenation builds the string, and calls toString(), before Log4j2 is even asked: one call with DEBUG off. Passing the object as a {} parameter costs nothing when disabled, because Log4j2 formats the message only after it has checked the level. But passing user.toString() as the parameter, which is what the first version of this article offered as the efficient option, calls it eagerly: one call with DEBUG off, the same as concatenation. The two forms that call nothing are a supplier (a lambda) and an explicit isDebugEnabled() guard. The code for all six is in the test (file ArgumentEvaluationTest.java):
            target[0] = measure(logger, user -> logger.debug("User: " + user));
            target[1] = measure(logger, user -> logger.debug("User: {}", user));
            target[2] = measure(logger, user -> logger.debug("User: {}", user.toString()));
            target[3] = measure(logger, user -> logger.debug(() -> "User: " + user));
            target[4] = measure(logger, user -> logger.debug("User: {}", () -> user.toString()));
            target[5] = measure(logger, user -> {
                if (logger.isDebugEnabled()) {
                    logger.debug("User: " + user);
                }
            });
Pass the object, not the string you built from it. logger.debug("User: {}", user) is free when DEBUG is off. logger.debug("User: {}", user.toString()) is not. If producing the value is expensive, wrap it in a supplier: logger.debug("User: {}", () -> user.toString()).
Going deeper: what the counts do not tell you The test counts calls to toString(), which is deterministic. It does not time anything. How much a disabled call costs in nanoseconds depends on the JVM and the arguments, and a benchmark that ignores dead-code elimination will mislead; the article JMH Tutorial: Writing Java Microbenchmarks That Don’t Lie covers how to measure that honestly. Primitive arguments such as System.currentTimeMillis() are evaluated eagerly in every form shown here, but they cost almost nothing, so the rule of thumb is about avoiding work, not avoiding arguments.
Going deeper

When Logback is still on the classpath, your Log4j2 configuration silently stops applying

Back to the exclusion in section 2, because this is the failure that wastes an afternoon. The module contains a second build, broken/pom.xml (file pom.xml), with the same sources and the same dependencies minus the four exclusions. The dependency tree shows why that matters: spring-boot-starter-logging arrives through the starters and drags Logback in next to Log4j2 (output file 12-dependency-tree.txt):
# mvn dependency:tree for broken/pom.xml (exclusions removed)
  com.ankurm:log4j2-levels-both-logging:jar:1.0.0
  +- org.springframework.boot:spring-boot-starter-webmvc:jar:4.1.2:compile
  |  \- org.springframework.boot:spring-boot-starter:jar:4.1.2:compile
  |     \- org.springframework.boot:spring-boot-starter-logging:jar:4.1.2:compile
  |        +- ch.qos.logback:logback-classic:jar:1.5.38:compile
  |        |  \- ch.qos.logback:logback-core:jar:1.5.38:compile
  |        +- org.apache.logging.log4j:log4j-to-slf4j:jar:2.25.5:compile
  |        \- org.slf4j:jul-to-slf4j:jar:2.0.20:compile
  \- org.springframework.boot:spring-boot-starter-log4j2:jar:4.1.2:compile
     +- org.apache.logging.log4j:log4j-slf4j2-impl:jar:2.25.5:compile
     |  +- org.apache.logging.log4j:log4j-api:jar:2.25.5:compile
     |  \- org.slf4j:slf4j-api:jar:2.0.20:compile
     +- org.apache.logging.log4j:log4j-core:jar:2.25.5:compile
     \- org.apache.logging.log4j:log4j-jul:jar:2.25.5:compile
The application starts without an error. What gives it away is SLF4J’s startup notes and what the logger does. I started it and asked the service package, which the XML sets to DEBUG, for its levels (output file 11-both-logging.txt):
$ curl 'localhost:18097/demo/log?name=com.ankurm.log4j2levels.service.Probe'   (the XML sets this package to DEBUG)
{"FATAL":true,"ERROR":true,"WARN":true,"DIAG":true,"INFO":true,"PERF":true,"DEBUG":false,"TRACE":false}
$ curl localhost:18097/actuator/loggers/com.ankurm.log4j2levels.service
{"effectiveLevel":"INFO"}
SLF4J(W): Class path contains multiple SLF4J providers.
SLF4J(W): Found provider [ch.qos.logback.classic.spi.LogbackServiceProvider@14acaea5]
SLF4J(W): Found provider [org.apache.logging.slf4j.SLF4JServiceProvider@46d56d67]
SLF4J(W): See https://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J(I): Actual provider is of type [ch.qos.logback.classic.spi.LogbackServiceProvider@14acaea5]
SLF4J found two providers and chose Logback. The package is INFO, not DEBUG, so log4j2-spring.xml was ignored. The lines that did print carry Spring Boot’s default Logback format rather than the pattern from the XML, FATAL came out as ERROR, DIAG as WARN and PERF as INFO, because Logback has no FATAL, DIAG or PERF; the transcript has the full set. I did not look into which component does that mapping.
The fingerprint: a Log4j2 configuration that does nothing and a startup that says SLF4J(W) about multiple providers. Run mvn dependency:tree -Dincludes=ch.qos.logback. If anything is listed, find the starter that still reaches spring-boot-starter-logging and exclude it there.
Going deeper

The article’s UserService, running at DEBUG and at INFO

The first version showed a UserService that could not compile, because it used types it never defined. The one in the repository compiles and runs (file UserService.java). It makes one real call per level:
    public User getUserById(Long userId) {
        logger.debug("Entering getUserById with userId: {}", userId);
        if (userId == null) {
            logger.warn("getUserById called with null userId");
            throw new IllegalArgumentException("User ID cannot be null");
        }
        try {
            logger.info("Fetching user with ID: {}", userId);
            User user = userRepository.findById(userId);
            if (user == null) {
                logger.info("User not found for ID: {}", userId);
                return null;
            }
            logger.debug("Successfully retrieved user: {}", user.username());
            return user;
        } catch (DatabaseException e) {
            logger.error("Database error while fetching user with ID: {}", userId, e);
            throw new ServiceException("Failed to retrieve user", e);
        }
    }
Running six scenarios against it with the service package at DEBUG gives 23 lines. Raising that package to INFO gives 17, and the six DEBUG lines are the difference. The repository’s package is configured at ERROR, so its DEBUG SELECT line never appears at either setting but its ERROR line does (output file 05-user-service.txt):
DEBUG c.a.l.s.UserService - Entering getUserById with userId: -1
INFO  c.a.l.s.UserService - Fetching user with ID: -1
ERROR c.a.l.d.UserRepository - connection reset while loading user -1
ERROR c.a.l.s.UserService - Database error while fetching user with ID: -1
com.ankurm.log4j2levels.db.DatabaseException: connection reset
	at com.ankurm.log4j2levels.db.UserRepository.findById(UserRepository.java:24)
INFO  c.a.l.s.UserService - Starting batch user processing
DEBUG c.a.l.s.UserService - Processed 2 users in batch
INFO  c.a.l.s.UserService - Batch processing completed, 2 processed
INFO  c.a.l.s.UserService - Starting batch user processing
ERROR c.a.l.d.UserRepository - connection reset while loading user -1
FATAL c.a.l.s.UserService - Critical failure in batch processing, giving up.
Each level did its job. DEBUG narrates entry and values, INFO marks each significant step, WARN flags the null id that was handled, ERROR records the failed query twice (once at the repository where it happened, once in the service that translated it), and FATAL marks the batch that gave up. Going deeper

Choosing a level for each message

Mechanics aside, the skill is picking the right level, and the discipline is doing it the same way across the team. Choose the right level for the job
  • FATAL: unrecoverable errors causing application shutdown (e.g. “Failed to bind to port”).
  • ERROR: handled exceptions, failed operations, and business logic violations (e.g. “Database connection failed”, “Payment processing error”).
  • WARN: deprecated API usage, unusual but handled situations, or configuration issues (e.g. “Cache miss”, “Using default configuration”).
  • INFO: normal application flow, startup and shutdown messages, and significant business events (e.g. “Service started”, “User [X] logged in”, “Order [Y] processed”).
  • DEBUG: detailed diagnostic information useful during development (e.g. “Entering method getUser”, “Variable [user] set to…”).
  • TRACE: extremely detailed flow, typically method entry and exit or loop iterations (e.g. “Loop iteration [i=5]”).
Configure for your environment. Keep production at INFO or WARN and raise DEBUG only for the packages you are working on; DEBUG or TRACE across the whole application in production adds both cost and noise, unless you are chasing a live incident. Sections 3 and 6 are what make that practical: one package at a time, changed without a redeploy. Keeping the configuration outside the packaged jar is a sound habit for the same reason, though this module keeps it inside to stay self-contained, and the properties and Actuator routes in section 6 need no external file at all. When you want the whole picture in one place, this is the summary table from the first version, with the numbers confirmed above:
LevelInt valueWhen to useProduction useExample scenario
OFF0Disable all logging.RareLogging temporarily disabled for compliance or security.
FATAL100Unrecoverable errors.Yes, alwaysApplication cannot start, critical data corruption.
ERROR200Failed operations, exceptions.Yes, alwaysDatabase connection failed, HTTP 500 error.
WARN300Handled exceptions, potential issues.Yes, recommendedDeprecated API usage, high memory usage alert.
INFO400Business process tracking.Yes, standardUser login, order placement, batch job start and end.
DEBUG500Troubleshooting data.No (unless debugging)Method parameters, variable values, SQL queries.
TRACE600Very detailed flow diagnostics.NeverLoop iterations, raw data dumps, method entry and exit.
ALLInteger.MAX_VALUEEnable everything.NeverExtreme, low-level debugging scenarios.
Adopt a consistent strategy across the team: write down which level each kind of message gets and review against it. Predictable logs are far easier to search, and treating the logging configuration as part of the deployment, not an afterthought, is what stops the levels that suit development from reaching production.
Should you use Log4j2 at all in a Spring Boot 4 application? Only if you have a reason. Boot’s default is Logback, everything in this article about logging.level.* and /actuator/loggers works the same on either, and the swap in section 2 is a dependency change you then have to keep correct on every starter, as section 8 shows. I did not benchmark Log4j2 against Logback, so this article makes no performance claim for either. Switch when something specific in Log4j2 earns it, for example a team that already runs Log4j2 elsewhere and wants one configuration format, and not because a guide told you to. One honest limit of what is here: custom levels are a Log4j2 feature that Spring Boot’s own level tooling does not understand, so a custom level costs you the runtime control of section 6 for that level.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.