Skip to content
Advertisement

Subclassing java.util.logging.Formatter doesn’t work

I am using java.util.logging for logging (I don’t want to use log4j or anything else).

This is my complete private logging.properties:

handlers= java.util.logging.FileHandler
.level= INFO
java.util.logging.FileHandler.pattern = my.log
java.util.logging.FileHandler.limit = 500000
java.util.logging.FileHandler.count = 40
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter

This is the code in my program:

public static Logger log = Logger.getLogger(MyClass.class.getName());
// Is there anything else to be init'ed here? 
// I don't. I just start using log directly in the code.

log.severe("something");
log.info("something else");

Since this gives each log message on 2 lines, I tried this

How do I get java logging output to appear on a single line?

Copied the LogFormatter class in the first reply exactly.

Changed one line in my logging.properties

java.util.logging.FileHandler.formatter = com.mycomp.myproj.LogFormatter;

Now my log has started appearing in XML. I have a strong feeling that the FileHandler doesn’t like my com.mycomp.myproj.LogFormatter and hence defaulting to the default XMLFormatter. How do I figure out why FileHandler isn’t using my LogFormatter class?

Advertisement

Answer

You can set the formatter in the code itself on the FileHandler instance.

import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

// please change name of your own choice
Logger log = Logger.getLogger("CustomLogger"); 
log.setUseParentHandlers(false);
log.setLevel(Level.ALL);

FileHandler handler = new FileHandler("[log_file_location]");
handler.setFormatter(new CustomFormatter()); // set formatter
log.addHandler(handler);

log.info("test message");

handler.close(); // close the handler at some later point in your application.

The CustomFormatter class is defined as follows.

import java.util.logging.Formatter;
import java.util.logging.LogRecord;

public class CustomFormatter extends Formatter {

    @Override
    public String format(LogRecord record) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(record.getMessage());
        return buffer.toString();
    }

}

You can code in CustomFormatter to output the messages in any format you want. Hope this helps.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement