如何在这个简单的 Java Logging 实现中附加到日志文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23698156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I append to log files in this simple Java Logging implementation?
提问by diegoaguilar
I got the following class to create and manage a Logger
. Whenever across the code and program execution, calls to static getLogger()
catch blocksare used to log.
我有以下课程来创建和管理Logger
. 每当跨越代码和程序执行时,都会使用对静态getLogger()
catch 块的调用来记录日志。
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.
但是,如何附加到这样的日志文件?我见过的所有示例都对这个实现进行了很大的改变,我喜欢它,因为它清晰、简短和简单。
采纳答案by calimbak
From the FileHandler
constructor, you can specify a boolean
to specify an append mode.
从FileHandler
构造函数中,您可以指定 aboolean
来指定附加模式。
Do as following:
执行以下操作:
fh = new FileHandler("%h/TorrentDownloader.log", true);
回答by Evgeniy Dorofeev
Use a different constructor
使用不同的构造函数
fh = new FileHandler("%h/TorrentDownloader.log", true);
回答by Owen Cao
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.
这个构造函数创建一个带有文件名模式的 FileHandler 和一个布尔值,告诉 FileHandler 是否应该附加到任何现有文件。
And this articlehas a full explanation.
这篇文章有一个完整的解释。