Java Util Logging - Creating a custom log Handler

[Updated: Sep 11, 2017, Created: Sep 11, 2017]

This example shows how to Write and register a custom java.util.logging.Handler. A Handler object receives the log messages from a Logger and uses them in any ways it wants. For example, it may write them to a console or write them to a file, or send them to an external logging service etc.

Example

Implementing the Handler

package com.logicbig.example;

import java.util.logging.Handler;
import java.util.logging.LogRecord;

public class MyLogHandler extends Handler {

  @Override
  public void publish(LogRecord record) {
      StringBuilder sb = new StringBuilder();
      sb.append(record.getMillis())
        .append(" - ")
        .append(record.getSourceClassName())
        .append("#")
        .append(record.getSourceMethodName())
        .append(" - ")
        .append(record.getMessage());
      System.out.println(sb.toString());
  }

  @Override
  public void flush() {
  }

  @Override
  public void close() throws SecurityException {
  }
}

Sending log message from application

package com.logicbig.example;

import java.util.logging.Logger;

public class AppClass {
  private static final Logger LOGGER = Logger.getLogger(AppClass.class.getName());

  public void doSomething(){
      LOGGER.info("in AppClass");
  }
}

Registering the custom Handler

We are going to remove all default Handlers and add our custom Handler:

package com.logicbig.example;

import java.util.logging.Handler;
import java.util.logging.LogManager;
import java.util.logging.Logger;

public class ExampleMain {

  public static void main(String[] args) {
      //reset() will remove all default handlers
      LogManager.getLogManager().reset();
      Logger rootLogger = LogManager.getLogManager().getLogger("");

      rootLogger.addHandler(new MyLogHandler());
      AppClass appClass = new AppClass();
      appClass.doSomething();
      rootLogger.info("some message");
  }
}

Output

1505156867089 - com.logicbig.example.AppClass#doSomething - in AppClass
1505156867089 - java.util.logging.LogManager$RootLogger#log - some message

Example Project

Dependencies and Technologies Used :

  • JDK 1.8
  • Maven 3.3.9

Custom Handler Example Select All Download
  • logging-custom-handler
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also