Java Logging Handlers, Filters and Formatters: Configuring java.util.logging
Go deeper into java.util.logging: ConsoleHandler and FileHandler, log file patterns and rotation, handler levels, filters, custom formatters and handlers, the SimpleFormatter format string, LogRecord details, and a practical logging recipe for real applications.
kvi5hnuCode Sprout team member11 min readOn this page
The previous article covered the frontend side of logging: getting a System.Logger, choosing levels and writing messages. A logger alone doesn't decide where messages end up or what they look like. In java.util.logging (JUL), that is the job of handlers, filters and formatters. This article explains each one, shows how to configure them in logging.properties and in code, and ends with a compact recipe you can use in your own projects.
Handlers
Loggers pass records to handlers, and handlers do the actual output. The simplest is ConsoleHandler, which prints records to System.err.
Each logger can have any number of handlers. By default, a logger also passes every record to its parent logger's handlers, all the way up to the root logger. The standard configuration attaches one ConsoleHandler to the root logger, so records from any logger end up on the console. That ConsoleHandler has level INFO by default.

To send records somewhere else, add another handler. JUL provides:
ConsoleHandler, which writes toSystem.err.FileHandler, which writes to files, with optional rotation.SocketHandler, which sends records to a host and port.StreamHandler, which writes to anyOutputStreamand is the base class of the first three.MemoryHandler, which buffers records in memory and pushes them to another handler only when a severe enough record arrives. That gives you the context around an error without logging everything.
To add a file handler alongside the console, list both in the configuration:
handlers=java.util.logging.ConsoleHandler,java.util.logging.FileHandler
By default, records go to a file javan.log in the user's home directory, where n is a number that makes the file name unique, and they're formatted as XML:
<record>
<date>2026-11-13T09:53:34.072Z</date>
<millis>1794563614072</millis>
<sequence>1</sequence>
<logger>com.mycompany.myapp</logger>
<level>INFO</level>
<class>com.mycompany.myapp.Employee</class>
<method>read</method>
<thread>1</thread>
<message>Opening file staff.txt</message>
</record>
FileHandler configuration
You can change the file handler's behavior with these properties:
| Property | Description | Default |
|---|---|---|
java.util.logging.FileHandler.level | The handler's level | Level.ALL |
java.util.logging.FileHandler.append | true to append to an existing file, false to start a new file on each run | false |
java.util.logging.FileHandler.limit | Approximate maximum bytes per file before the next is opened (0 = no limit) | 0 (no limit) |
java.util.logging.FileHandler.pattern | File name pattern (see below) | %h/java%u.log |
java.util.logging.FileHandler.count | Number of files in the rotation sequence | 1 |
java.util.logging.FileHandler.filter | Class name of a filter | none |
java.util.logging.FileHandler.encoding | Character encoding | platform default |
java.util.logging.FileHandler.formatter | Class name of the formatter | java.util.logging.XMLFormatter |
java.util.logging.FileHandler.maxLocks | Maximum number of concurrent locks (Java 9+) | 100 |
You'll usually want your own file name. The pattern can contain these variables:
| Variable | Meaning |
|---|---|
%h | The user's home directory (the user.home property) |
%t | The system's temporary directory |
%u | A unique number to resolve conflicts, for example when two programs log at once |
%g | The generation number of rotated logs. If rotation is on and the pattern has no %g, .%g is appended |
%% | A literal percent sign |
For example, %h/myapp%u.log gives each run of the application its own log in your home directory.
Log rotation
For long-running programs, turn on rotation by setting limit and count. Files form a sequence such as myapp.log.0, myapp.log.1, myapp.log.2. When the current file exceeds the size limit, the oldest file is deleted, the others are renamed one generation up, and a new generation 0 file is started. Generation 0 is always the newest.
Filters
Besides filtering by level, each handler (and each logger) can have a filter. Filter is a functional interface:
boolean isLoggable(LogRecord record)
In code, a lambda does the job:
handler.setFilter(record -> record.getMessage().contains("order"));
In the configuration file, name a class that implements Filter and has a no-argument constructor:
java.util.logging.ConsoleHandler.filter=com.mycompany.myapp.OrderFilter
Formatters
ConsoleHandler uses SimpleFormatter (two lines of text per record), and FileHandler uses XMLFormatter. For anything else, write your own: extend java.util.logging.Formatter and override
String format(LogRecord record)
Format the record any way you like and return the string. Inside format, call
String formatMessage(LogRecord record)
to get the message part: it looks up the key in a resource bundle if there is one, and fills in {0}-style parameters.
Many file formats need a header and a footer around the records, such as the opening and closing tags of an XML document or the brackets of a JSON array. For that, override
String getHead(Handler h)
String getTail(Handler h)
Both return the empty string by default. Then install your formatter:
java.util.logging.FileHandler.formatter=com.mycompany.myapp.MyFormatter
Customizing SimpleFormatter without writing code
Often you just want a different one-line layout. SimpleFormatter takes a java.util.Formatter (printf-style) format string from the property java.util.logging.SimpleFormatter.format. You can set it in the logging configuration, or as a system property with -D. The arguments are:
| Argument | Content |
|---|---|
%1$ | The record's time as a ZonedDateTime, for use with t conversions |
%2$ | The source: class and method, or the logger name |
%3$ | The logger name |
%4$ | The level (localized name) |
%5$ | The formatted message |
%6$ | The exception with its stack trace, preceded by a newline, or empty |
For a compact single-line format with an ISO-style timestamp:
java.util.logging.SimpleFormatter.format=%1$tF %1$tT %4$-7s [%3$s] %5$s%6$s%n
which prints lines like 2026-11-13 09:53:34 INFO [com.mycompany.myapp] Opening file data.txt.
Writing your own handler
When none of the built-in handlers fit, for example to show log records in a GUI window or send them to a chat channel, extend Handler, or StreamHandler if you have an OutputStream. Handler has three abstract methods:
public class ListHandler extends Handler {
private final List<String> lines = new CopyOnWriteArrayList<>();
@Override
public void publish(LogRecord record) {
if (!isLoggable(record)) return; // checks level and filter
lines.add(getFormatter().format(record));
}
@Override public void flush() { }
@Override public void close() { lines.clear(); }
public List<String> lines() { return lines; }
}
Set a formatter with setFormatter(new SimpleFormatter()) before using it. A handler that shows records in a window works the same way: extend StreamHandler, pass it an OutputStream whose write methods append text to a text area, and call flush() after each published record so the text appears immediately.
A logging recipe
With so many options, it's easy to lose track of the essentials. Here's the recipe for a typical application:
-
Pick a logger. For a simple application, one logger named after the main package is fine, such as
com.mycompany.myprog. In classes that log a lot, keep it in a field:javaprivate static final System.Logger logger = System.getLogger("com.mycompany.myprog");Larger applications typically use one logger per class (named after the class), so levels can be tuned per component.
-
Configure the backend. The default JUL configuration logs
INFOand above to the console. To change that, create alogging.propertiesfile:texthandlers=java.util.logging.ConsoleHandler,java.util.logging.FileHandler com.mycompany.myprog.level=FINER java.util.logging.ConsoleHandler.level=FINE java.util.logging.FileHandler.pattern=%h/myprog%u.logand start the program with:
textjava -Djava.util.logging.config.file=logging.properties MainClass -
Log instead of printing. Whenever you're tempted to call
System.out.printlnfor diagnostics, emit a log message instead:javalogger.log(TRACE, "File open dialog canceled");And log unexpected exceptions with their stack traces:
javatry { . . . } catch (SomeException e) { logger.log(WARNING, "Explanation of what failed", e); }
Configuring in code
Everything in the properties file can also be done through the JUL API, which is handy in tests and small tools:
Logger.getLogger(name)returns the JUL logger behindSystem.getLogger(name).logger.setLevel(level)sets the logger's level.logger.addHandler(handler)andlogger.removeHandler(handler)attach and detach handlers.logger.setUseParentHandlers(false)stops records from also reaching the parent logger's handlers, which would otherwise print them twice.handler.setLevel(level),handler.setFilter(filter)andhandler.setFormatter(formatter)configure a handler.
The demo uses these calls. It attaches a one-line formatter, a filtered handler and a rotating FileHandler in a temporary directory. It then prints what ended up in each file and deletes the files.
import static java.lang.System.Logger.Level.*;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.logging.*;
public class Solution {
public static void main(String[] args) throws IOException {
// the JUL logger behind System.getLogger("com.mycompany.shop")
Logger jul = Logger.getLogger("com.mycompany.shop");
jul.setLevel(Level.FINE);
jul.setUseParentHandlers(false); // don't also send records to the root's ConsoleHandler
// 1. a handler with a custom formatter that writes to System.out
var console = new StreamHandler(System.out, new OneLineFormatter()) {
@Override
public synchronized void publish(LogRecord record) {
super.publish(record);
flush();
}
};
console.setLevel(Level.INFO); // the handler's own gate
jul.addHandler(console);
System.Logger logger = System.getLogger("com.mycompany.shop");
logger.log(INFO, "Shop started");
logger.log(DEBUG, "passes the logger (FINE) but not the console handler (INFO)");
logger.log(WARNING, "Low stock for {0}: {1} left", "SKU-7", 2);
logger.log(ERROR, "Payment failed", new IOException("gateway timeout"));
// 2. a second handler with a filter: only records that mention an order
var orders = new ByteArrayOutputStream();
var orderHandler = new StreamHandler(orders, new OneLineFormatter());
orderHandler.setLevel(Level.ALL);
orderHandler.setFilter(record -> record.getMessage().contains("order"));
jul.addHandler(orderHandler);
logger.log(INFO, "Received order 1001");
logger.log(DEBUG, "Recomputed prices");
logger.log(DEBUG, "Packed order 1001");
orderHandler.flush();
System.out.print("order log:\n" + orders);
jul.removeHandler(orderHandler);
// 3. a FileHandler with rotation: 3 files of about 120 bytes each
Path dir = Files.createTempDirectory("logdemo");
var file = new FileHandler(dir + "/shop%g.log", 120, 3, false);
file.setFormatter(new OneLineFormatter());
file.setLevel(Level.ALL);
jul.addHandler(file);
jul.removeHandler(console);
for (int i = 1; i <= 8; i++) logger.log(INFO, "Shipped order " + (1000 + i));
file.close();
try (var files = Files.list(dir)) {
for (Path p : files.sorted().toList()) {
List<String> lines = Files.readAllLines(p);
System.out.println(p.getFileName() + ": " + lines.size() + " records, first: "
+ (lines.isEmpty() ? "-" : lines.get(0)));
Files.delete(p);
}
}
Files.delete(dir);
}
}
/** Formats each record as a single line: LEVEL logger.method - message [exception]. */
class OneLineFormatter extends java.util.logging.Formatter {
@Override
public String format(LogRecord r) {
var sb = new StringBuilder();
sb.append(String.format("%-7s %s.%s - %s", r.getLevel(), r.getLoggerName(),
r.getSourceMethodName(), formatMessage(r))); // formatMessage fills in {0}, {1}
if (r.getThrown() != null) sb.append(" [").append(r.getThrown()).append(']');
return sb.append(System.lineSeparator()).toString();
}
}
INFO com.mycompany.shop.main - Shop started
WARNING com.mycompany.shop.main - Low stock for SKU-7: 2 left
SEVERE com.mycompany.shop.main - Payment failed [java.io.IOException: gateway timeout]
INFO com.mycompany.shop.main - Received order 1001
order log:
INFO com.mycompany.shop.main - Received order 1001
FINE com.mycompany.shop.main - Packed order 1001
shop0.log: 2 records, first: INFO com.mycompany.shop.main - Shipped order 1007
shop1.log: 3 records, first: INFO com.mycompany.shop.main - Shipped order 1004
shop2.log: 3 records, first: INFO com.mycompany.shop.main - Shipped order 1001
Points to notice:
- The
DEBUGrecord passed the logger (levelFINE) but not the console handler (levelINFO). formatMessagefilled in the{0}and{1}parameters.- The filtered handler kept only the two records that mention an order, including a
FINEone, because its own level isALL. - With a 120-byte limit and a count of 3, the eight records were spread over three files.
shop0.logholds the newest records, and records 1001–1003 sit inshop2.log. Had there been more, the oldest would have been dropped.
Common questions
Why are my log messages printed twice?
The record reached two handlers: one on your logger and the one inherited from the root logger. Call logger.setUseParentHandlers(false), or don't add a second console handler and configure the root's handler instead.
How do I log in JSON?
Write a small Formatter that turns each LogRecord into a single-line JSON object, escaping quotes and newlines. Alternatively, use Logback or Log4j 2 with their JSON layouts. One record per line is what log collectors expect.
Is FileHandler safe to use from several threads?
Yes. JUL handlers synchronise publish, so concurrent log calls don't interleave within a record. Multiple processes writing the same pattern get separate files thanks to the %u unique-number variable and lock files.
Where should my application send logs in a container? To standard output or standard error, one record per line. The container platform collects, rotates and ships them. Writing rotating files inside a container is usually unnecessary, and the files may be lost when the container restarts.
Can I change log levels without restarting?
With JUL, yes: through JMX (java.util.logging:type=Logging, for example in JConsole), or by calling LogManager.getLogManager().updateConfiguration(...) (Java 9) from code. Logback and Log4j 2 can also watch their configuration files for changes.
API reference
java.util.logging.Handler
| Method | Description |
|---|---|
abstract void publish(LogRecord record) | Sends the record to its destination |
abstract void flush() | Flushes buffered data |
abstract void close() | Flushes and releases resources |
Filter getFilter(), void setFilter(Filter f) | The handler's filter |
Formatter getFormatter(), void setFormatter(Formatter f) | The handler's formatter |
Level getLevel(), void setLevel(Level l) | The handler's level |
boolean isLoggable(LogRecord record) | Checks level and filter |
java.util.logging.ConsoleHandler: ConsoleHandler() constructs a handler for System.err.
java.util.logging.FileHandler
| Constructor | Description |
|---|---|
FileHandler(String pattern) | Writes to files named by the pattern |
FileHandler(String pattern, boolean append) | Optionally appends to an existing file |
FileHandler(String pattern, int limit, int count) | Rotates through count files of about limit bytes |
FileHandler(String pattern, int limit, int count, boolean append) | Rotation plus append |
FileHandler(String pattern, long limit, int count, boolean append) | The same with a long limit (Java 9) |
java.util.logging.LogRecord
| Method | Description |
|---|---|
Level getLevel() | The record's level |
String getLoggerName() | The name of the logger that produced it |
ResourceBundle getResourceBundle(), String getResourceBundleName() | The bundle for localizing the message, or null |
String getMessage() | The raw message, before localization and formatting |
Object[] getParameters() | The parameters, or null |
Throwable getThrown() | The exception, or null |
String getSourceClassName(), String getSourceMethodName() | The logging code's location, supplied by the caller or inferred from the stack. May be inaccurate for optimized code |
long getMillis(), Instant getInstant() | Creation time (getInstant since Java 9) |
long getSequenceNumber() | A unique sequence number |
long getLongThreadID() | The creating thread's ID (Java 16). Replaces the deprecated int getThreadID(), since long-running programs can exceed Integer.MAX_VALUE thread IDs |
java.util.logging.Filter: boolean isLoggable(LogRecord record) returns true if the record should be logged.
java.util.logging.Formatter
| Method | Description |
|---|---|
abstract String format(LogRecord record) | Formats one record |
String getHead(Handler h), String getTail(Handler h) | Text before and after all records. Empty by default |
String formatMessage(LogRecord record) | The localized message with parameters filled in |
Summary
- Handlers write records. Records also flow to parent loggers' handlers unless
setUseParentHandlers(false). ConsoleHandlerwrites toSystem.err(default levelINFO).FileHandlerwrites to files (XML by default) with patterns like%h/myapp%u.log.SocketHandler,StreamHandlerandMemoryHandlercover other needs.- Set
limitandcountto rotate log files. Generation 0 is the newest. - A record must pass the logger's level, then the handler's level and filter.
- Customize output with a
Formattersubclass (format,formatMessage,getHead,getTail), or simply with theSimpleFormatter.formatproperty. - Write a custom handler by extending
HandlerorStreamHandler. - Recipe: one logger per package or class in a static field, a
logging.propertiesfile passed with-Djava.util.logging.config.file, log instead of print, and log unexpected exceptions with their stack traces.
Practice Questions
A record is logged at FINE. The logger's level is FINE, and the ConsoleHandler's level is INFO. Is it printed?
No. It passes the logger's level check but is rejected by the handler's level. Both gates must be passed.
Why might every log message appear twice on the console?
A ConsoleHandler was added to your logger while the root logger also has one, so each record is published by both. Remove one handler, or call setUseParentHandlers(false) on your logger.
With pattern %h/app%g.log, limit 1000000 and count 5, which file contains the most recent records, and how many files can exist?
app0.log in the home directory holds the newest records. At most 5 files exist (app0.log to app4.log). When rotation would need a sixth, the oldest is deleted.
In a custom Formatter, why call formatMessage(record) instead of record.getMessage()?
getMessage returns the raw message, possibly a bundle key with {0} placeholders. formatMessage localizes it and substitutes the parameters.
What SimpleFormatter.format pattern prints just the level and the message, each record on one line?
%4$s: %5$s%6$s%n. Argument 4 is the level, 5 the message, 6 the optional exception, and %n ends the line.
When would you use MemoryHandler?
When you want detailed context around failures without writing every detailed record. It buffers recent records in memory and pushes them to a target handler only when a record at or above its push level, such as SEVERE, arrives.
Previous: Java Logging Basics: System.Logger and java.util.logging
Next: Java Debugging Tips: Practical Techniques Beyond the Debugger
Related reading
- Java Logging Basics: System.Logger and java.util.logging
- 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

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.