Java Logging Basics: System.Logger and java.util.logging
Get started with logging in Java: frontends versus backends, the platform System.Logger API, log levels, lazy messages with suppliers, logging exceptions, MessageFormat placeholders, and configuring java.util.logging with logging.properties and logger hierarchies.
kvi5hnuCode Sprout team member12 min readOn this page
Every Java programmer knows the routine. Something misbehaves, so you sprinkle System.out.println calls through the code, find the problem, and delete the print statements, only to add them back when the next problem appears. Logging ends this cycle. Log statements stay in the code permanently. A configuration file, not a code change, decides which of them produce output, where that output goes, and what it looks like.
Which logging framework?
Java ships with a logging framework in the package java.util.logging, often abbreviated JUL. It isn't the only option. Log4j 2 and Logback offer more features and are widely used in industry.
Logging libraries come in two layers:
- The frontend (or facade) is the API that programmers call to log messages.
- The backend filters, formats and writes those messages somewhere. Deployers configure it, usually through a configuration file, without touching the code.

If you write a library, you shouldn't force a backend on the applications that use it. Use a facade so each application can route messages to its preferred backend. SLF4J is the most common facade, with a pleasant API. The JDK has its own minimal facade, the platform logging API (System.Logger, introduced in Java 9 by JEP 264).
This article and the next use System.Logger as frontend and java.util.logging as backend. That's a reasonable choice when the simple frontend is enough, because you can swap the backend later without touching your logging calls. JUL has fewer features than its competitors, but it is enough for many programs, and its simplicity is also a security advantage.
Studying the platform API and JUL also teaches you the concepts that every logging framework shares: loggers, levels, hierarchies, handlers (called appenders elsewhere) and formatters (layouts).
Logging 101
Platform loggers implement the interface System.Logger. Every logger has a name. The name can be anything, but by convention it's the package name, or the fully qualified class name, of the code that logs:
System.Logger logger = System.getLogger("com.mycompany.myapp");
The first request for a name creates the logger, and later requests for the same name return the same logger. Classes that log a lot usually keep it in a constant:
private static final System.Logger logger = System.getLogger("com.mycompany.myapp");
Now log:
logger.log(System.Logger.Level.INFO, "Opening file " + filename);
With the default JUL configuration, the record appears on the console like this:
Nov 13, 2026 9:53:34 AM com.mycompany.myapp.Main read
INFO: Opening file data.txt
The timestamp, class and method were added automatically.
To silence informational messages when the program is deployed, configure the backend. For JUL, create a file logging.properties:
handlers=java.util.logging.ConsoleHandler
com.mycompany.myapp.level=WARNING
and start the program with:
java -Djava.util.logging.config.file=logging.properties MainClass
INFO is below WARNING, so the message no longer appears. Note the split of responsibilities: obtaining a logger and calling log belong to the frontend. Destinations, formatting, filtering and configuration belong to the backend.
The platform logging API
Levels
Every message has a level. System.Logger.Level has these values, in decreasing severity:
| Level | Typical use |
|---|---|
ERROR | Something failed. An operation couldn't complete |
WARNING | Something is wrong or suspicious, but the program continues |
INFO | Significant normal events: startup, shutdown, configuration, completed jobs |
DEBUG | Details useful when diagnosing problems |
TRACE | Very fine-grained flow, such as method entry and exit or loop iterations |
There are also ALL and OFF, used for configuration rather than for logging individual messages.
A static import keeps calls short:
import static java.lang.System.Logger.Level.*;
. . .
logger.log(INFO, "Opening file " + filename);
You can ask whether a level is currently enabled with logger.isLoggable(DEBUG).
Lazy messages
In the call above, "Opening file " + filename is concatenated even if the message is discarded. For a cheap string that doesn't matter. If building the message is costly, for example dumping a large data structure, pass a lambda instead:
logger.log(DEBUG, () -> "Cache contents: " + cache.dump());
The Supplier<String> is called only if the message will actually be logged. The demo below counts the calls to prove it.
Logging exceptions
Logging an exception is common. Pass it as the last argument, and the log includes the stack trace:
catch (IOException ex) {
logger.log(WARNING, "Cannot open file " + filename, ex);
}
Prefer this to ex.printStackTrace(). The trace ends up wherever the logs go, with a timestamp and level, and it can be filtered.
Message formats
You can also log a pattern with parameters:
logger.log(WARNING, "Cannot open file {0}", filename);
Log messages can be localized with resource bundles (covered with internationalization later). Pass the bundle and a key:
logger.log(WARNING, bundle, "file.bad", filename); // looks up file.bad in the bundle
Alternatively, obtain a localized logger with System.getLogger("com.mycompany.myapp", bundle). Then every String message or format you pass is treated as a key in the bundle. The overloads that take an Object or Supplier<String> are unaffected.
Not every combination of these features (supplier, throwable, parameters, bundle) has its own overload. The API table at the end lists those that exist.
Configuring java.util.logging
The default backend for the platform logging API is java.util.logging. Everything from here on is specific to that backend.
The default configuration is in the file conf/logging.properties inside the JDK installation. To use your own file, set the system property java.util.logging.config.file when starting the program:
java -Djava.util.logging.config.file=configFile MainClass
Logger levels
Set the level of your own loggers by appending .level to the logger name:
com.mycompany.myapp.level=WARNING
The root logger's name is the empty string, so its level is set with:
.level=WARNING
For historical reasons, JUL's levels have different names from the platform API's, and the configuration file uses the JUL names:
Platform logging (System.Logger.Level) | java.util.logging.Level |
|---|---|
ERROR | SEVERE |
WARNING | WARNING |
INFO | INFO |
DEBUG | FINE |
TRACE | FINER |
JUL also has CONFIG (between INFO and FINE) and FINEST (below FINER), which the platform API doesn't use.
The logger hierarchy
Logger names are hierarchical, like package names, and the hierarchy actually means something. A logger without its own level inherits the level of its nearest configured ancestor. So setting com.mycompany to OFF silences all its descendants too.

Handler levels: the second gate
Loggers don't write anything themselves. They pass records to handlers, and handlers have levels too. The default ConsoleHandler only prints INFO and above. So to actually see DEBUG/FINE messages on the console, you need both lines:
com.mycompany.myapp.level=FINE
java.util.logging.ConsoleHandler.level=FINE
Forgetting the second line is the classic "why don't my debug messages appear?" problem. The next article covers handlers in detail.
You can also change logger levels in a running program with jconsole or JMX tools, through the java.util.logging:type=Logging management bean.
A complete example
A real program would use a logging.properties file. This demo configures JUL from a string in code, so that it can send records to System.out in a compact format without timestamps and the output stays reproducible. The SimpleFormatter.format property shown is a real JUL setting (explained in the next article).
import static java.lang.System.Logger.Level.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.logging.*;
public class Solution {
private static final System.Logger logger = System.getLogger("com.mycompany.myapp");
private static int expensiveCalls = 0;
public static void main(String[] args) throws IOException {
configureBackend();
// 1. the five platform levels; this logger is configured at FINE (= DEBUG)
logger.log(ERROR, "error message");
logger.log(WARNING, "warning message");
logger.log(INFO, "Opening file data.txt");
logger.log(DEBUG, "debug message");
logger.log(TRACE, "trace message (filtered out)");
System.out.println("TRACE loggable? " + logger.isLoggable(TRACE)
+ ", DEBUG loggable? " + logger.isLoggable(DEBUG));
// 2. string concatenation always runs; a Supplier runs only if the record is logged
logger.log(TRACE, "state: " + expensiveState());
logger.log(TRACE, () -> "state: " + expensiveState());
logger.log(DEBUG, () -> "state: " + expensiveState());
System.out.println("expensiveState() was called " + expensiveCalls + " times");
// 3. MessageFormat placeholders, not printf
String filename = "staff.txt";
logger.log(INFO, "Cannot open file {0} after {1} attempts", filename, 3);
logger.log(INFO, "Write '{'n'}' for literal braces; it''s {0}", "easy");
// 4. logging an exception includes its stack trace
try {
throw new FileNotFoundException(filename);
} catch (IOException ex) {
logger.log(WARNING, "Cannot open file " + filename, ex);
}
// 5. logger names are hierarchical: the child has its own level, WARNING
System.Logger db = System.getLogger("com.mycompany.myapp.db");
db.log(INFO, "connected (filtered out: below WARNING)");
db.log(WARNING, "slow query took 2300 ms");
// a logger without its own level inherits from its nearest configured ancestor
System.Logger ui = System.getLogger("com.mycompany.myapp.ui.dialogs");
ui.log(DEBUG, "inherits FINE from com.mycompany.myapp");
// 6. the same name gives the same underlying java.util.logging logger
System.out.println(Logger.getLogger("com.mycompany.myapp") == Logger.getLogger("com.mycompany.myapp"));
}
static String expensiveState() {
expensiveCalls++;
return "42 items";
}
/**
* What a logging.properties file would normally do; done in code here so the
* demo prints to System.out without timestamps.
*/
static void configureBackend() throws IOException {
String config = """
handlers=
.level=INFO
com.mycompany.myapp.level=FINE
com.mycompany.myapp.db.level=WARNING
java.util.logging.SimpleFormatter.format=%4$s [%3$s] %5$s%6$s%n
""";
LogManager.getLogManager().readConfiguration(
new ByteArrayInputStream(config.getBytes(StandardCharsets.UTF_8)));
var handler = new StreamHandler(System.out, new SimpleFormatter()) {
@Override
public synchronized void publish(LogRecord record) {
super.publish(record);
flush();
}
};
handler.setLevel(Level.ALL);
Logger.getLogger("").addHandler(handler);
}
}
SEVERE [com.mycompany.myapp] error message
WARNING [com.mycompany.myapp] warning message
INFO [com.mycompany.myapp] Opening file data.txt
FINE [com.mycompany.myapp] debug message
TRACE loggable? false, DEBUG loggable? true
FINE [com.mycompany.myapp] state: 42 items
expensiveState() was called 2 times
INFO [com.mycompany.myapp] Cannot open file staff.txt after 3 attempts
INFO [com.mycompany.myapp] Write {n} for literal braces; it's easy
WARNING [com.mycompany.myapp] Cannot open file staff.txt
java.io.FileNotFoundException: staff.txt
at Solution.main(Solution.java:36)
WARNING [com.mycompany.myapp.db] slow query took 2300 ms
FINE [com.mycompany.myapp.ui.dialogs] inherits FINE from com.mycompany.myapp
true
Points to notice:
- The
TRACErecord never appeared.TRACEmaps toFINER, below the configuredFINE. expensiveState()ran twice: once for the string concatenation, even though thatTRACErecord was discarded, and once for theDEBUGsupplier. TheTRACEsupplier never ran.- The
dbchild logger has its own level,WARNING. Theui.dialogslogger inheritedFINE. - The printed level names are JUL's:
SEVEREandFINE.
Common questions
Should I use System.Logger, JUL, SLF4J or Log4j 2?
Libraries should log through a facade, either System.Logger (no dependency) or SLF4J (most common), so that applications choose the backend. Applications often use SLF4J with Logback or Log4j 2 for their rich configuration. System.Logger with JUL is enough for small tools and programs without dependencies.
Why don't my DEBUG messages appear?
Two gates must allow them: the logger's level and the handler's level. JUL's default ConsoleHandler stops at INFO. Set both, for example com.example.level=FINE and java.util.logging.ConsoleHandler.level=FINE.
Is string concatenation in log calls a performance problem?
Only when it happens for messages that are discarded and the concatenation is expensive. Use the Supplier<String> overload (logger.log(DEBUG, () -> "state " + dump())) or parameterised messages. SLF4J's {} placeholders avoid the formatting cost too.
Should log messages contain user input? Often they must, for debugging, but treat that input as untrusted. Strip or escape line breaks to prevent forged log lines, never log passwords or tokens, and keep logging libraries patched. Log4Shell showed that a backend feature can turn logged input into code execution.
What's the difference between JUL levels and System.Logger levels?
They are two naming schemes for the same idea. System.Logger uses ERROR, WARNING, INFO, DEBUG and TRACE, which JUL maps to SEVERE, WARNING, INFO, FINE and FINER. JUL configuration files always use the JUL names.
API reference: java.lang.System.Logger (Java 9)
| Method | Description |
|---|---|
String getName() | The logger's name |
boolean isLoggable(System.Logger.Level level) | Whether messages at this level are processed |
void log(Level level, String msg) | Logs a message |
void log(Level level, String msg, Throwable thrown) | Logs a message and an exception with its stack trace |
void log(Level level, Object obj) | Logs obj.toString() |
void log(Level level, Supplier<String> msgSupplier) | Calls the supplier only if the level is loggable |
void log(Level level, Supplier<String> msgSupplier, Throwable thrown) | The same, with an exception |
void log(Level level, String format, Object... params) | Logs a MessageFormat pattern with parameters |
void log(Level level, ResourceBundle bundle, String format, Object... params) | Looks up format as a key in bundle (if not null), then formats with the parameters |
void log(Level level, ResourceBundle bundle, String msg, Throwable thrown) | Looks up msg in bundle (if not null) and logs it with the exception |
System.getLogger(String name) and System.getLogger(String name, ResourceBundle bundle) obtain loggers.
Summary
- Logging replaces throwaway print statements with permanent, configurable output.
- A frontend (
System.Logger, SLF4J) is the API you call. A backend (java.util.logging, Logback, Log4j 2) filters, formats and writes. Libraries should log through a facade. - Get a logger with
System.getLogger(name), conventionally the package or class name, and keep it in aprivate static finalfield. - Levels:
ERROR,WARNING,INFO,DEBUG,TRACE. In JUL configuration they areSEVERE,WARNING,INFO,FINE,FINER. - Use a
Supplierlambda for expensive messages. Pass exceptions as the last argument to log their stack trace. - Format patterns use
MessageFormatsyntax ({0}), notprintf. - Configure JUL with a file given by
-Djava.util.logging.config.file. Setname.levelfor loggers, and remember that handlers have their own levels. - Loggers inherit levels from their nearest configured ancestor in the name hierarchy.
Practice Questions
What is the difference between a logging frontend and a backend?
The frontend is the API code calls to emit messages (for example System.Logger or SLF4J). The backend decides which messages are kept, how they're formatted and where they go (for example java.util.logging or Logback), and is configured by deployers.
Why would a library author prefer a facade like SLF4J or System.Logger over calling Log4j directly?
So applications using the library can choose their own backend. A library that hard-wires a backend forces it, and its configuration and dependencies, on every application that uses the library.
logger.log(DEBUG, "Tree: " + tree.render()) is slow even when debug logging is off. Why, and how do you fix it?
The argument is evaluated before log is called, so render() runs and the string is built regardless of the level. Use a supplier: logger.log(DEBUG, () -> "Tree: " + tree.render()). It is only invoked if DEBUG is enabled.
What does logger.log(INFO, "It's {0}", "late") print?
Its {0}, without the parameter, because the lone apostrophe starts a quoted section in MessageFormat. Write It''s {0} to get It's late.
You set com.mycompany.myapp.level=FINE but DEBUG messages still don't show on the console. What's missing?
The ConsoleHandler has its own level, INFO by default. Add java.util.logging.ConsoleHandler.level=FINE (or lower).
Logger com.mycompany has level OFF and com.mycompany.billing has no level set. Does com.mycompany.billing log WARNING messages?
No. It inherits OFF from its nearest configured ancestor, com.mycompany.
Why does java -Dcom.mycompany.myapp.level=FINE MyApp not change the logger's level?
Logger levels are logging-configuration properties read from the configuration file, not system properties. Only the file's location, java.util.logging.config.file, is given with -D.
Previous: Java Assertions: Using assert, Enabling Assertions and Design by Contract
Next: Java Logging Handlers, Filters and Formatters: Configuring java.util.logging
Related reading
- Java Assertions: Using assert, Enabling Assertions and Design by Contract
- Java Exception Handling Best Practices: Tips Every Developer Should Know
- Java finally and try-with-resources: Cleaning Up and Reading Stack Traces
- Catching Exceptions in Java: try/catch, Multi-catch, Rethrowing and Chaining
- Throwing Exceptions and Creating Custom Exception Classes in Java

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.