Java : SimpleFormatter (logging) with Examples

SimpleFormatter (Java SE 17 & JDK 17) API Examples.
You will find code examples on most SimpleFormatter methods.


Summary

Print a brief summary of the LogRecord in a human readable format. The summary will typically be 1 or 2 lines.

Class diagram

final var logger = Logger.getLogger("com.example.logging");
logger.setUseParentHandlers(false);

// The ConsoleHandler has the SimpleFormatter by default.
final var handler = new ConsoleHandler();
System.out.println(handler.getFormatter()); // java.util.logging.SimpleFormatter@d76b01a

logger.addHandler(handler);

logger.info("TEST LOG : 1");
logger.info("TEST LOG : 2");
logger.info("TEST LOG : 3");

// Result
// ↓
//Mar 18, 2022 12:07:30 AM com.example.logging.SimpleFormatterTest$1 method
//INFO: TEST LOG : 1
//Mar 18, 2022 12:07:30 AM com.example.logging.SimpleFormatterTest$1 method
//INFO: TEST LOG : 2
//Mar 18, 2022 12:07:30 AM com.example.logging.SimpleFormatterTest$1 method
//INFO: TEST LOG : 3

Constructors

SimpleFormatter ()

Create a SimpleFormatter.

final var logger = Logger.getLogger("com.example.logging");
logger.setUseParentHandlers(false);

final var pattern = Path.of("R:", "java-work", "log.txt");
final var handler = new FileHandler(pattern.toString());
logger.addHandler(handler);

System.out.println(handler.getFormatter()); // java.util.logging.XMLFormatter@2c83f1d1

handler.setFormatter(new SimpleFormatter());

System.out.println(handler.getFormatter()); // java.util.logging.SimpleFormatter@79acc4ff

logger.info("TEST LOG!");

System.out.print(Files.readString(pattern));

// Result
// ↓
//Mar 18, 2022 12:08:02 AM com.example.logging.SimpleFormatterTest$2 method
//INFO: TEST LOG!

Methods

String format (LogRecord record)

Format the given LogRecord.

class MyFormatter extends SimpleFormatter {
    @Override
    public String format(LogRecord logRecord) {
        logRecord.setMessage(logRecord.getMessage() + " : override format!");
        return super.format(logRecord);
    }
}

final var logger = Logger.getLogger("com.example.logging");
logger.setUseParentHandlers(false);

final var handler = new ConsoleHandler();
logger.addHandler(handler);

handler.setFormatter(new MyFormatter());

logger.info("TEST LOG!");

// Result
// ↓
//Mar 18, 2022 12:08:44 AM com.example.logging.SimpleFormatterTest$3 method
//INFO: TEST LOG! : override format!

Methods declared in Formatter

formatMessage, getHead, getTail

Please see the link below.


Related posts

To top of page