Creating a custom log message format

This post explains how to create a custom log message format.

Out of the box java provides two log formats SimpleFormatter and XMLFormatter.

Both extends the abstract super class Formatter.

We can create our own custom format.

Below is the code of the custom format

CustomFormatter


1  package Logging;
2  
3  import java.util.logging.Formatter;
4  import java.util.logging.LogRecord;
5  
6  public class CustomFormatter extends Formatter {
7   @Override
8   public String format(LogRecord logRecord) {
9       StringBuilder sb = new StringBuilder();
10      sb.append(logRecord.getThreadID()).append(":");
11      sb.append(logRecord.getLoggerName()).append(":");
12      sb.append(logRecord.getLevel()).append(":");
13      sb.append(logRecord.getMessage());
14      return sb.toString();
15  }
16 }

In the above code we create CustomFormatter class which extends the java provided abstract class Formatter like the other classes mentioned previously.

We need to provide implementation for abstract method “format” in our custom class.

According to format method syntax it takes LogRecord as a parameter.

LogRecord represents each log message that has to logged. We create our own format by using the information provided by LogRecord, as shown from line 9 to 14
in the format method.

After creating our own formatter, we set it to our handler. It is the handler instance which actually do the logging.

In our example it is a FileHandler, we create an instance of CustomFormatter at line 10. We set the custom formatter by calling the method setFormatter as shown in the below code at line 12.

Main Code


1  package Logging;
2  
3  import java.io.IOException;
4  import java.util.logging.FileHandler;
5  import java.util.logging.Logger;
6  
7  public class LoggingDemo5 {
8   public static void main(String[] args) throws IOException {
9       Logger logger = Logger.getLogger("logger1");
10      CustomFormatter customFormatter = new CustomFormatter();
11      FileHandler fileHandler = new FileHandler("java.log");
12      fileHandler.setFormatter(customFormatter);
13      logger.addHandler(fileHandler);
14      logger.info("Hello my name is World");
15      fileHandler.close();
16  }
17 }

Output

1:logger1:INFO:Hello my name is World

Leave a Reply