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.
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.
From the FileHandler
constructor, you can specify a boolean
to specify an append mode.
Do as following:
fh = new FileHandler("%h/TorrentDownloader.log", true);
Use a different constructor
fh = new FileHandler("%h/TorrentDownloader.log", true);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With