How can I append to log files in this simple Java Logging implementation?
Asked Answered
R

3

7

I got the following class to create and manage a Logger. Whenever across the code and program execution, calls to static getLogger() catch blocks are used to log.

public class Log {
    private static final Logger logger = Logger.getLogger("MyLog");  

    public static void iniciarLog() throws IOException {
        FileHandler fh;  

        try { 
//          fh = new FileHandler(System.getProperty("user.home")+System.getProperty("file.separator")+"TorrentDownloader.log");  
            fh = new FileHandler("%h/TorrentDownloader.log");  
            logger.addHandler(fh);
            SimpleFormatter formatter = new SimpleFormatter();  
            fh.setFormatter(formatter);  

            logger.info("Se inició el log"); 
        } catch (SecurityException | IOException e) {  
            logger.severe("Error al crear el log");
        } 
    }

    public static Logger getLogger() {
        return logger;
    }
}

However, how can I append to such logging file? All examples I've seen change a lot this implementation which I like as it's clear, brief and simple.

Rosenblatt answered 16/5, 2014 at 14:42 Comment(0)
K
13

From the FileHandler constructor, you can specify a boolean to specify an append mode.

Do as following:

fh = new FileHandler("%h/TorrentDownloader.log", true);  
Kleper answered 16/5, 2014 at 14:51 Comment(5)
Thanks, can you extend more about the count parameter?Rosenblatt
Oops ... my bad, i misread the documentation, it's a default behaviour. I will update my answer.Kleper
But, how would it change to use that constructor giving a different count?Rosenblatt
It limit the number of files created with the limit parameter. Check the link in my answer for more information.Kleper
Thanks. By the way, do you have experience with FX and data binding? I got this doubt: #23731404Rosenblatt
J
2

Use a different constructor

fh = new FileHandler("%h/TorrentDownloader.log", true);  
Jaquez answered 16/5, 2014 at 14:50 Comment(0)
N
2

You can use this constructor:

FileHandler handler = new FileHandler(String pattern, boolean append);

and in your case, it's:

fh = new FileHandler("%h/TorrentDownloader.log", true);

This constructor creates a FileHandler with a file name pattern, and a boolean telling whether the FileHandler should append to any existing files or not.

And this article has a full explanation.

Nonperformance answered 16/5, 2014 at 14:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.