Log errors with java.util.logging
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A log is the program's diary: a record of what happened, when, and how serious it was. Java's built-in java.util.logging gives you named loggers, levels, and handlers that write to the console or a file, which is everything printStackTrace lacks.
Logger.getLogger and levels
Logging records what a program does and what goes wrong, with levels such as INFO, WARNING and SEVERE, so problems can be traced later.
A logger is a named object that you send log messages to; it decides which messages are kept and where they go. Java's built-in one lives in java.util.logging, and each class usually gets its own: private static final Logger LOG = Logger.getLogger(FeeService.class.getName());.
Example 1 · Levels with the default console output
import java.util.logging.Level;import java.util.logging.Logger;
public class LoggerLevelsDemo { private static final Logger LOG = Logger.getLogger(LoggerLevelsDemo.class.getName());
public static void main(String[] args) { LOG.severe("Fee database not reachable"); LOG.warning("Fee for roll 102 is 10 days late"); LOG.info("Fee reminders sent to 25 students"); LOG.config("Reminder batch size is 25"); LOG.fine("Checking roll 101"); LOG.log(Level.INFO, "Receipt sent to roll {0}", "101"); }}Oct 15, 2026 10:30:12 AM LoggerLevelsDemo main SEVERE: Fee database not reachable Oct 15, 2026 10:30:12 AM LoggerLevelsDemo main WARNING: Fee for roll 102 is 10 days late Oct 15, 2026 10:30:12 AM LoggerLevelsDemo main INFO: Fee reminders sent to 25 students Oct 15, 2026 10:30:12 AM LoggerLevelsDemo main INFO: Receipt sent to roll 101
What this code does
- All of this appears on
System.err, two lines per message: the date, time, class and method, then the level and text. Your dates and times will differ. CONFIGandFINEare belowINFO, so the default settings drop them. Inlog(Level.INFO, "... {0}", "101")the{0}is filled with the argument.
Every message has a level that says how important it is. From highest to lowest: SEVERE (something failed), WARNING (something looks wrong), INFO (normal milestones), CONFIG, then FINE, FINER and FINEST (detail for debugging). Each level has a method of the same name: LOG.warning("..."). With the JDK's default settings, the console shows INFO and above, written to System.err (red in most IDEs), with the date, the class and the method on a first line. Messages below INFO are dropped.
Logging an exception with log(Level.SEVERE, message, e)
LOG.log(Level.SEVERE, message, e) logs your message together with the whole exception: its class, message, stack trace and every Caused by: section. This is the form to use in a catch block.
Example 2 · Log the exception, not just its message
import java.io.IOException;import java.util.logging.Level;import java.util.logging.Logger;
class StorageException extends RuntimeException { StorageException(String message, Throwable cause) { super(message, cause); }}
public class LogExceptionDemo { static { // only for this page: log lines on System.out, without the date line System.setErr(System.out); System.setProperty("java.util.logging.SimpleFormatter.format", "%4$s: %5$s%6$s%n"); }
private static final Logger LOG = Logger.getLogger(LogExceptionDemo.class.getName());
static void writeReceipt(String roll) throws IOException { throw new IOException("disk is full"); }
static void saveReceipt(String roll) { try { writeReceipt(roll); } catch (IOException e) { throw new StorageException("Could not save receipt for roll " + roll, e); } }
public static void main(String[] args) { try { saveReceipt("101"); } catch (StorageException e) { LOG.severe(e.getMessage()); // weak: one line, no trace, no cause LOG.log(Level.SEVERE, "Receipt step failed", e); // good: everything } }}SEVERE: Could not save receipt for roll 101 SEVERE: Receipt step failed StorageException: Could not save receipt for roll 101 at LogExceptionDemo.saveReceipt(LogExceptionDemo.java:27) at LogExceptionDemo.main(LogExceptionDemo.java:33) Caused by: java.io.IOException: disk is full at LogExceptionDemo.writeReceipt(LogExceptionDemo.java:20) at LogExceptionDemo.saveReceipt(LogExceptionDemo.java:25) ... 1 more
What this code does
- The
staticblock only makes the default console handler print toSystem.outwith a short format, so the output fits this page. Real programs leave the defaults or use a config file. LOG.severe(e.getMessage())gives one line.LOG.log(Level.SEVERE, "...", e)adds the stack trace and theCaused by: java.io.IOException: disk is fullsection, which tells a developer exactly where and why it failed.
LOG.severe(e.getMessage()) looks similar but keeps only one line of text. The stack trace and the cause are gone, so the log says what failed but not where or why. For values, LOG.log(Level.INFO, "Receipt sent to roll {0}", roll) fills {0} in only when the message is actually logged. For costly messages, LOG.fine(() -> buildReport()) takes a lambda that runs only when FINE is enabled.
Writing logs to a file with FileHandler
A handler receives the messages a logger keeps and writes them somewhere. ConsoleHandler writes to System.err; FileHandler writes to a file: new FileHandler("fees.log", true), where true means append to the file instead of replacing it.
Example 3 · Send logs to a file with FileHandler
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;import java.util.logging.FileHandler;import java.util.logging.Level;import java.util.logging.Logger;import java.util.logging.SimpleFormatter;
public class FileLogDemo { public static void main(String[] args) throws IOException { // Short format without the date, so the file content below is the same on every run System.setProperty("java.util.logging.SimpleFormatter.format", "%4$s %5$s%6$s%n"); Path folder = Files.createTempDirectory("logs"); Path logFile = folder.resolve("fees.log");
Logger log = Logger.getLogger("fees"); log.setUseParentHandlers(false); FileHandler file = new FileHandler(logFile.toString(), true); file.setFormatter(new SimpleFormatter()); // plain lines instead of XML log.addHandler(file);
log.info("Fee reminder job started"); log.warning("Roll 102 has not paid for 10 days"); log.log(Level.SEVERE, "Could not send SMS to roll 103", new IOException("SMS gateway timeout")); file.close(); // flushes and removes the .lck file
List<String> lines = Files.readAllLines(logFile); System.out.println("Contents of " + logFile.getFileName() + ":"); lines.forEach(System.out::println);
Files.delete(logFile); Files.delete(folder); }}Contents of fees.log: INFO Fee reminder job started WARNING Roll 102 has not paid for 10 days SEVERE Could not send SMS to roll 103 java.io.IOException: SMS gateway timeout at FileLogDemo.main(FileLogDemo.java:25)
What this code does
setUseParentHandlers(false)stops the message from also reaching the root logger's console handler, so everything goes only tofees.log.- Without
setFormatter(new SimpleFormatter())the file would hold XML records.file.close()writes everything out and deletes thefees.log.lcklock file, so the folder can be cleaned up.
Two details trip people up. A FileHandler writes XML by default, so call setFormatter(new SimpleFormatter()) for plain lines. And it keeps the file open with a .lck lock file next to it until you call close(). For long-running programs, new FileHandler("fees%g.log", 1_000_000, 5, true) rotates: when a file reaches about 1 MB it starts a new one, keeping at most 5 (%g becomes 0, 1, 2…).
logging.properties
A logging.properties file sets up loggers, levels, handlers and formats without changing code. Start the program with -Djava.util.logging.config.file=logging.properties and Java reads it at startup.
java -Djava.util.logging.config.file=logging.properties FeeAppExample 4 · Configure levels and a file in logging.properties
import java.io.IOException;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.util.logging.LogManager;import java.util.logging.Logger;
public class LoggingConfigDemo { public static void main(String[] args) throws IOException { Path folder = Files.createTempDirectory("logcfg"); Path logFile = folder.resolve("app.log"); Path config = folder.resolve("logging.properties");
String text = """ handlers = java.util.logging.FileHandler .level = INFO fees.level = FINE java.util.logging.FileHandler.pattern = LOGFILE java.util.logging.FileHandler.level = FINE java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter java.util.logging.SimpleFormatter.format = %3$s %4$s %5$s%n """; Files.writeString(config, text.replace("LOGFILE", logFile.toString().replace('\\', '/')));
// What -Djava.util.logging.config.file=logging.properties does at startup try (InputStream in = Files.newInputStream(config)) { LogManager.getLogManager().readConfiguration(in); }
Logger fees = Logger.getLogger("fees"); Logger hostel = Logger.getLogger("hostel"); fees.fine("Checking roll 101"); hostel.fine("Checking room A-12"); hostel.info("Room A-12 allotted"); LogManager.getLogManager().reset(); // closes the FileHandler
Files.readAllLines(logFile).forEach(System.out::println);
Files.delete(logFile); Files.delete(config); Files.delete(folder); }}fees FINE Checking roll 101 hostel INFO Room A-12 allotted
What this code does
.level = INFOapplies to every logger, butfees.level = FINElowers it for thefeeslogger only. Sofeeskeeps itsFINEline, whilehosteldrops itsFINEline and keeps onlyINFO.- The handler's own level is
FINE, so it passes what the loggers keep. The format%3$s %4$s %5$sprints the logger name, the level and the message; the path uses forward slashes because a backslash is an escape character in properties files.
A message is written only when it passes two filters: the logger's level and the handler's level. fees.level=FINE lets the fees logger keep FINE messages, but a handler with level=INFO still drops them. When debug lines do not appear, check both.
Why printStackTrace is not logging
e.printStackTrace() writes the trace to System.err and nothing more: no level, no time, no logger name. A logger call, shown below, gives the same trace plus all of that.
} catch (IOException e) { e.printStackTrace(); // not logging: no level, no time, no file}
} catch (IOException e) { LOG.log(Level.SEVERE, "Could not save receipt for roll " + roll, e); // logging}printStackTrace cannot be switched off or filtered, and it cannot be sent to a file without redirecting the whole error stream. On a server, that output is often lost.
In real projects you will also meet SLF4J with Logback or Log4j 2; the ideas (named loggers, levels, handlers, configuration) are the same.
Next step
Check your understanding
12 quick questions