Explain Codes LogoExplain Codes Logo

How to write logs in text file when using java.util.logging.Logger

java
logging
java-logging
file-handling
Anton ShumikhinbyAnton Shumikhin·Aug 25, 2024
TLDR

Here's an instant solution to log messages to a file with java.util.logging.Logger:

Logger logger = Logger.getLogger("MyLog"); try { // Because why not write our logs to a file, right? FileHandler fh = new FileHandler("ItsLogTime.log", true); logger.addHandler(fh); // Adding spice to our logging with a touch of SimpleFormatter. fh.setFormatter(new SimpleFormatter()); // "Hello, it's me, the log message. You were looking for me, right?" logger.info("Log message"); } catch (SecurityException | IOException e) { logger.log(Level.SEVERE, "Oops! The FileHandler broke.", e); }

This simple snippet sets up logging to MyLogFile.log, appends new messages, and formats them using SimpleFormatter.

Overview of java.util.logging components

First off, let's grapple with the core components of logging:

  • The Logger is your personal log broadcaster.
  • The Handler makes crucial decisions of where to pass the logs.
  • The Formatter is the beautification agent for your logs.

Avoid console outputs

Make sure your logs only land in the file, and nowhere else by:

logger.setUseParentHandlers(false); // "Console? Never heard of it!"

Adding timestamp to the log filename

Time-travel is not possible, yet. So let's timestamp our log files:

String pattern = "yyyyMMddhhmmss"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String date = simpleDateFormat.format(new Date()); // "Back to the future, Marty!" FileHandler fh = new FileHandler("MyLogFile_" + date + ".log");

Making Formatter bend to your will

Customize formatters by implementing the Formatter interface:

class MyFormatter extends Formatter { @Override public String format(LogRecord record) { // "You didn't think it'd be this easy, right?" } }

Externalize using a configuration file

Fancy external configurations? Use logging.properties:

java.util.logging.FileHandler.pattern = %h/java%u.log java.util.logging.FileHandler.limit = 50000 java.util.logging.FileHandler.count = 1 java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter

Setting the right log level

Control log verbosity with log levels:

// "I can show you the log. Shining, shimmering, splendid!" logger.setLevel(Level.FINEST); // Change as necessary

Exception handling and clean-up

Ensure a clean exit in your logging procedures:

// "Clean-up at aisle log. Clean-up at aisle log." fh.close();

Providing file access permissions

Check the permissions and paths for log files to avoid distressing surprises.

Delving into advanced nuances

Juggling with large log files

When the log outgrows our perceptions of size, its rotation time:

// "500MB ought to be enough for anyone." FileHandler fh = new FileHandler("MyLog%g.log", 500 * 1024 * 1024, 10, true);

Logger inheritance

Inherit logs with precision:

Logger parentLogger = Logger.getLogger("com.myapp"); Logger childLogger = Logger.getLogger("com.myapp.module"); childLogger.setUseParentHandlers(true); // "Log, I am your Logger."

Understanding log levels

  • SEVERE: Catastrophic
  • WARNING: Dubious
  • INFO: FYI
  • CONFIG: Insider info
  • FINE, FINER, FINEST: Tea leaves

Tuning JVM parameters

Set it and forget it with JVM parameters:

-Djava.util.logging.config.file=path/to/logging.properties