W3docs

How to write logs in text file when using java.util.logging.Logger

To write logs to a text file using java.util.logging.Logger, you will need to do the following:

To write logs to a text file using java.util.logging.Logger, you will need to do the following:

  1. Create a FileHandler that writes to a text file, and specify the logging format.
  2. Add the FileHandler to your Logger instance.
  3. Use the Logger instance to log messages as needed.

Here is a complete, runnable example that combines these steps, includes the necessary imports, handles IOException, and properly closes the logger to prevent resource leaks:

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class LogToFileExample {
    public static void main(String[] args) {
        Logger logger = Logger.getLogger("MyLog");
        try {
            FileHandler fileHandler = new FileHandler("mylog.txt");
            SimpleFormatter formatter = new SimpleFormatter();
            fileHandler.setFormatter(formatter);
            logger.addHandler(fileHandler);

            logger.info("This is a log message");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            logger.close();
        }
    }
}

That's it! Your log messages will now be written to the text file mylog.txt.

I hope this helps. Let me know if you have any questions.