Java Util Logging - Creating a custom log Handler

[Last Updated: 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.


Implementing the Handler

package com.logicbig.example;

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

public class MyLogHandler extends Handler {

  public void publish(LogRecord record) {
      StringBuilder sb = new StringBuilder();
        .append(" - ")
        .append(" - ")

  public void flush() {

  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(){"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
      Logger rootLogger = LogManager.getLogManager().getLogger("");

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


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