Changing the default log message format

In this post I will be explaining how to change the default log message format provided by java util loggging.

In case of logging to console (done by ConsoleHandler), the default format used is an instance of java.util.logging.SimpleFormatter.

In case of logging to file (done by FileHandler), the default format used is an instance of java.util.logging.XMLFormatter.

In our example we will be changing the default format used by FileHandler.

We will configure the FileHandler to use SimpleFormatter instead of XMLFormatter.

Below is the code

Main Code


1  package Logging;
2  
3  import java.io.IOException;
4  import java.util.logging.FileHandler;
5  import java.util.logging.Logger;
6  import java.util.logging.SimpleFormatter;
7  
8  public class LoggingDemo4 {
9   public static void main(String[] args) throws IOException {
10      Logger logger = Logger.getLogger("logger1");
11      SimpleFormatter simpleFormatter = new SimpleFormatter();
12      FileHandler fileHandler = null;
13      try {
14          fileHandler = new FileHandler("java.log");
15          fileHandler.setFormatter(simpleFormatter);
16          logger.addHandler(fileHandler);
17          logger.info("Hello my name is Sumanth");
18      } finally {
19          fileHandler.close();
20      }
21  }
22 }

Explanation

At line 11, we create an instance of SimpleFormatter.

At line 14, we create an instance of FileHandler, passing “java.log” as file name. The file will be created in the project classpath.

At line 15, we change the default formatter by calling setFormatter method on fileHandler instance.

Output (java.log)

Jul 01, 2017 4:22:55 PM Logging.LoggingDemo4 main
INFO: Hello my name is Sumanth

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s