Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 568
diegoaguilar Avatar asked May 16 '14 14:05

diegoaguilar


People also ask

How do you add logs in Java?

The process of creating a new Logger in Java is quite simple. You have to use Logger. getLogger() method. The getLogger() method identifies the name of the Logger and takes string as a parameter.


3 Answers

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

Do as following:

fh = new FileHandler("%h/TorrentDownloader.log", true);  
like image 184
calimbak Avatar answered Oct 02 '22 13:10

calimbak


Use a different constructor

fh = new FileHandler("%h/TorrentDownloader.log", true);  
like image 32
Evgeniy Dorofeev Avatar answered Oct 02 '22 14:10

Evgeniy Dorofeev


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.

like image 45
Owen Cao Avatar answered Oct 02 '22 13:10

Owen Cao