每天都有Java.util.logger新文件 [英] Java.util.logger new file every day
问题描述
我正在使用java.util.logging框架在我的JSF应用程序中实现日志记录.我已经成功实现了这一点,但是我有一个新的要求,即每天轮换日志并创建一个新的日志文件.
I am using java.util.logging framework to implement logging in my JSF application. I have successfully done implementing this, but however I have a new requirement to rotate the logs and create a new log file for each day.
我无法弄清楚如何实现.任何有关实施的提示将不胜感激.谢谢.
I am not able to figure out how this can be implemented. Any hints on implementation would be highly appreciated. Thanks.
这是我配置记录器的方式:
This is how I have configured my logger:
myLogger = Logger.getLogger("info.aio");
fileHandler = new FileHandler("aioinfo.log", 1048576, 100, true);
fileHandler.setFormatter(new SimpleFormatter());
myLogger.addHandler(fileHandler);
推荐答案
Since you are using code to setup your FileHandler then you can add code to close and recreate the FileHandler using the '%g'.
public static void main(String[] args) throws Exception {
//create aioinfo0.log.
install();
//rename aioinfo0.log to aioinfo1.log and create aioinfo0.log.
install();
}
private static final Logger myLogger = Logger.getLogger("info.aio");
private static volatile FileHandler fileHandler;
private static void install() throws IOException {
FileHandler fh = fileHandler;
if (fh != null) {
myLogger.removeHandler(fh);
fh.close(); //Release any file lock.
}
fileHandler = rotate("aioinfo%g.log", 1048576, 100, true);
fileHandler.setFormatter(new SimpleFormatter());
myLogger.addHandler(fileHandler);
}
private static FileHandler rotate(String pattern, int limit, int count, boolean append) throws IOException {
if (pattern == null) {
LogManager m = LogManager.getLogManager();
String p = FileHandler.class.getName();
pattern = m.getProperty(p + ".pattern");
if (pattern == null) {
pattern = "%h/java%u.log";
}
}
new FileHandler(pattern, 0, count, false).close(); //Trigger rotate.
return new FileHandler(pattern, limit, count, append);
}
If you want it to work automatically you can simply create a proxy handler for the FileHandler to handle closing and recreating files each day.
这篇关于每天都有Java.util.logger新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!