Java: Custom message format for Logger

I was looking for a way to configure output of Logger messages.

Solution is pretty simple and was found here Example: Creating custom formatters with java.util.logging.

1. add a class for custom formatting

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

/**
 * MyCustomFormatter formats the LogRecord as follows:
 * date   level   localized message with parameters 
 */
public class LogFormatter extends Formatter {

	public LogFormatter () {
		super();
	}

	public String format(LogRecord record) {
		
		// Create a StringBuffer to contain the formatted record
		// start with the date.
		StringBuffer sb = new StringBuffer();
		
		// Get the date from the LogRecord and add it to the buffer
		Date date = new Date(record.getMillis());
		sb.append(date.toString());
		sb.append(" ");
		
		// Get the level name and add it to the buffer
		sb.append(record.getLevel().getName());
		sb.append(" ");
		 
		// Get the formatted message (includes localization 
		// and substitution of paramters) and add it to the buffer
		sb.append(formatMessage(record));
		sb.append("\n");

		return sb.toString();
	}
}

1. set custom formatting in your code:

Logger logger = Logger.getLogger("MyLog");
        FileHandler fh;
        try {

            // This block configure the logger with handler and formatter
            fh = new FileHandler("mylog.log");
            logger.addHandler(fh);
            Formatter formatter = new LogFormatter();
            fh.setFormatter(formatter);

            logger.setLevel(Level.ALL);
            // the following statement is used to log any messages
            logger.info("My first log");

        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

Leave a Reply

%d bloggers like this: