Java : FileHandler (logging) with Examples

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


Summary

Simple file logging Handler.

Class diagram

final var pattern = Path.of("R:", "java-work", "log.txt");
System.out.println(pattern); // R:\java-work\log.txt

final var handler = new FileHandler(pattern.toString());
handler.setFormatter(new SimpleFormatter());

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

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

// --- PowerShell ---
//PS R:\java-work> ls -name
//log.txt
//
//PS R:\java-work> cat .\log.txt
//Jan 10, 2023 11:45:03 PM com.example.logging.FileHandlerTest$1 method
//INFO: TEST LOG : 1
//Jan 10, 2023 11:45:03 PM com.example.logging.FileHandlerTest$1 method
//INFO: TEST LOG : 2

Constructors

FileHandler ()

Construct a default FileHandler.

final var handler = new FileHandler();

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

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

logger.info("TEST LOG!");

// By default, the output file name is generated as "%h/java%u.log".
// Example on Windows 10 : C:\Users\xxxx\java0.log  (xxxx is the user name.)

// --- PowerShell ---
//PS C:\Users\xxxx> cat .\java0.log
//<?xml version="1.0" encoding="UTF-8" standalone="no"?>
//<!DOCTYPE log SYSTEM "logger.dtd">
//<log>
//<record>
//  <date>2022-03-16T05:07:18.168677300Z</date>
//  <millis>1647407238168</millis>
//  <nanos>677300</nanos>
//  <sequence>1</sequence>
//  <logger>com.example.logging</logger>
//  <level>INFO</level>
//  <class>com.example.logging.FileHandlerTest</class>
//  <method>constructor</method>
//  <thread>1</thread>
//  <message>TEST LOG!</message>
//</record>
//</log>

FileHandler (String pattern)

Initialize a FileHandler to write to the given filename.

final var pattern = Path.of("R:", "java-work", "log.txt");
System.out.println(pattern); // R:\java-work\log.txt

final var handler = new FileHandler(pattern.toString());
handler.setFormatter(new SimpleFormatter());

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

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

// --- PowerShell ---
//PS R:\java-work> ls -name
//log.txt
//
//PS R:\java-work> cat .\log.txt
//Mar 16, 2022 12:40:31 AM com.example.logging.FileHandlerTest$2 method
//INFO: TEST LOG : 1
//Mar 16, 2022 12:40:31 AM com.example.logging.FileHandlerTest$2 method
//INFO: TEST LOG : 2

Exit the program and execute the code below. Log by overwriting the previous output. (Append mode is false)

final var pattern = Path.of("R:", "java-work", "log.txt");
System.out.println(pattern); // R:\java-work\log.txt

final var handler = new FileHandler(pattern.toString());
handler.setFormatter(new SimpleFormatter());

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

logger.info("TEST LOG : 3");
logger.info("TEST LOG : 4");

// --- PowerShell ---
//PS R:\java-work> cat .\log.txt
//Mar 16, 2022 12:42:29 AM com.example.logging.FileHandlerTest$3 method
//INFO: TEST LOG : 3
//Mar 16, 2022 12:42:29 AM com.example.logging.FileHandlerTest$3 method
//INFO: TEST LOG : 4

FileHandler (String pattern, boolean append)

Initialize a FileHandler to write to the given filename, with optional append.

Please see also : FileHandler(String pattern)

final var pattern = Path.of("R:", "java-work", "log.txt");
System.out.println(pattern); // R:\java-work\log.txt

final var handler = new FileHandler(pattern.toString(), true);
handler.setFormatter(new SimpleFormatter());

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

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

// --- PowerShell ---
//PS R:\java-work> ls -name
//log.txt
//
//PS R:\java-work> cat .\log.txt
//Mar 16, 2022 12:44:50 AM com.example.logging.FileHandlerTest$4 method
//INFO: TEST LOG : 1
//Mar 16, 2022 12:44:50 AM com.example.logging.FileHandlerTest$4 method
//INFO: TEST LOG : 2

Exit the program and execute the code below. Log without overwriting the previous output. (Append mode is true)

final var pattern = Path.of("R:", "java-work", "log.txt");
System.out.println(pattern); // R:\java-work\log.txt

final var handler = new FileHandler(pattern.toString(), true);
handler.setFormatter(new SimpleFormatter());

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

logger.info("TEST LOG : 3");
logger.info("TEST LOG : 4");

// --- PowerShell ---
//PS R:\java-work> cat .\log.txt
//Mar 16, 2022 12:44:50 AM com.example.logging.FileHandlerTest$4 method
//INFO: TEST LOG : 1
//Mar 16, 2022 12:44:50 AM com.example.logging.FileHandlerTest$4 method
//INFO: TEST LOG : 2
//Mar 16, 2022 12:45:06 AM com.example.logging.FileHandlerTest$5 method
//INFO: TEST LOG : 3
//Mar 16, 2022 12:45:06 AM com.example.logging.FileHandlerTest$5 method
//INFO: TEST LOG : 4

FileHandler (String pattern, int limit, int count)

Initialize a FileHandler to write to a set of files.

class MoreSimpleFormatter extends Formatter {
    @Override
    public String format(LogRecord record) {
        return record.getLevel() + " : " + record.getMessage() + "\n";
    }
}

final var pattern = Path.of("R:", "java-work", "log_%g.txt");
System.out.println(pattern); // R:\java-work\log_%g.txt

final var handler = new FileHandler(pattern.toString(), 512, 3);
handler.setFormatter(new MoreSimpleFormatter());

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

for (int i = 0; i < 20; i++) {
    logger.info("TEST LOG : " + i);
}

// --- PowerShell ---
//PS R:\java-work> ls
// ...
//Mode                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          2022/03/16    15:30            410 log_0.txt
//-a---          2022/03/16    15:30              0 log_0.txt.lck
//
//PS R:\java-work> cat .\log_0.txt
//INFO : TEST LOG : 0
//INFO : TEST LOG : 1
// ...
//INFO : TEST LOG : 18
//INFO : TEST LOG : 19

for (int i = 20; i < 40; i++) {
    logger.info("TEST LOG : " + i);
}

// --- PowerShell ---
//PS R:\java-work> ls
// ...
//Mode                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          2022/03/16    15:30            315 log_0.txt
//-a---          2022/03/16    15:30              0 log_0.txt.lck
//-a---          2022/03/16    15:30            515 log_1.txt
//
//
//PS R:\java-work> cat .\log_0.txt
//INFO : TEST LOG : 25
//INFO : TEST LOG : 26
// ...
//INFO : TEST LOG : 38
//INFO : TEST LOG : 39
//
//PS R:\java-work> cat .\log_1.txt
//INFO : TEST LOG : 0
//INFO : TEST LOG : 1
// ...
//INFO : TEST LOG : 23
//INFO : TEST LOG : 24

for (int i = 40; i < 60; i++) {
    logger.info("TEST LOG : " + i);
}

// --- PowerShell ---
//PS R:\java-work> ls
// ...
//Mode                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          2022/03/16    15:30            210 log_0.txt
//-a---          2022/03/16    15:30              0 log_0.txt.lck
//-a---          2022/03/16    15:30            525 log_1.txt
//-a---          2022/03/16    15:30            515 log_2.txt
//
//PS R:\java-work> cat .\log_0.txt
//INFO : TEST LOG : 50
//INFO : TEST LOG : 51
// ...
//INFO : TEST LOG : 58
//INFO : TEST LOG : 59
//
//PS R:\java-work> cat .\log_1.txt
//INFO : TEST LOG : 25
//INFO : TEST LOG : 26
// ...
//INFO : TEST LOG : 48
//INFO : TEST LOG : 49
//
//PS R:\java-work> cat .\log_2.txt
//INFO : TEST LOG : 0
//INFO : TEST LOG : 1
// ...
//INFO : TEST LOG : 23
//INFO : TEST LOG : 24

for (int i = 60; i < 80; i++) {
    logger.info("TEST LOG : " + i);
}

// --- PowerShell ---
//PS R:\java-work> ls
// ...
//Mode                 LastWriteTime         Length Name
//----                 -------------         ------ ----
//-a---          2022/03/16    15:30            105 log_0.txt
//-a---          2022/03/16    15:30              0 log_0.txt.lck
//-a---          2022/03/16    15:30            525 log_1.txt
//-a---          2022/03/16    15:30            525 log_2.txt
//
//PS R:\java-work> cat .\log_0.txt
//INFO : TEST LOG : 75
//INFO : TEST LOG : 76
//INFO : TEST LOG : 77
//INFO : TEST LOG : 78
//INFO : TEST LOG : 79
//
//PS R:\java-work> cat .\log_1.txt
//INFO : TEST LOG : 50
//INFO : TEST LOG : 51
// ...
//INFO : TEST LOG : 73
//INFO : TEST LOG : 74
//
//PS R:\java-work> cat .\log_2.txt
//INFO : TEST LOG : 25
//INFO : TEST LOG : 26
// ...
//INFO : TEST LOG : 48
//INFO : TEST LOG : 49

FileHandler (String pattern, int limit, int count, boolean append)

Initialize a FileHandler to write to a set of files with optional append.

Please see FileHandler(String pattern, int limit, int count), FileHandler(String pattern, boolean append).

FileHandler (String pattern, long limit, int count, boolean append)

Initialize a FileHandler to write to a set of files with optional append.

Please see FileHandler(String pattern, int limit, int count, boolean append).

Methods

void close ()

Close all the files.

final var pattern = Path.of("R:", "java-work", "log.txt");
System.out.println(pattern); // R:\java-work\log.txt

final var handler = new FileHandler(pattern.toString());

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

logger.info("TEST LOG!");

logger.removeHandler(handler);
handler.close();

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

// Result
// ↓
//<?xml version="1.0" encoding="UTF-8" standalone="no"?>
//<!DOCTYPE log SYSTEM "logger.dtd">
//<log>
//<record>
//  <date>2022-03-16T06:53:39.983693700Z</date>
//  <millis>1647413619983</millis>
//  <nanos>693700</nanos>
//  <sequence>1</sequence>
//  <logger>com.example.logging</logger>
//  <level>INFO</level>
//  <class>com.example.logging.FileHandlerTest</class>
//  <method>close</method>
//  <thread>1</thread>
//  <message>TEST LOG!</message>
//</record>
//</log>

void publish (LogRecord record)

Format and publish a LogRecord.

final var pattern = Path.of("R:", "java-work", "log.txt");
System.out.println(pattern); // R:\java-work\log.txt

final var handler = new FileHandler(pattern.toString()) {
    @Override
    public synchronized void publish(LogRecord logRecord) {
        logRecord.setMessage(logRecord.getMessage() + ":override publish!");

        super.publish(logRecord);
    }
};
handler.setFormatter(new SimpleFormatter());

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

logger.info("TEST LOG!");

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

// Result
// ↓
//Mar 16, 2022 12:46:43 AM com.example.logging.FileHandlerTest$7 method
//INFO: TEST LOG!:override publish!

Methods declared in StreamHandler

flush, isLoggable, setEncoding, setOutputStream

Please see the link below.

Methods declared in Handler

getEncoding, getErrorManager, getFilter, getFormatter, getLevel, reportError, setErrorManager, setFilter, setFormatter, setLevel

Please see the link below.


Related posts

To top of page