[英]DailyFileRolling without log4j & logback
我正在尋找一個簡單的每日文件滾動實用程序,該實用程序將在<filename>-yyyy-mm-dd.txt
create file
具有當前date
的<filename>-yyyy-mm-dd.txt
,並將繼續在其上書寫,並且當date
更改時,它將create a new file
& continue
寫。
在谷歌搜索時,我得到的大多數結果是使用logback or log4j
。
有沒有什么方法可以在without
logback或log4j的 without
獲得Java中的每日文件滾輪?
假設您正在談論java.util.logging
您將必須實現自己的java.util.logging.Handler
。
我自己還沒有嘗試過,但是看看Tomcat
的JULI
包,他們實現了一個應該能夠執行滾動文件記錄的Handler
。 該類是org.apache.juli.FileHandler
,可以在maven Central(版本9.0.0M4)上找到。
我所做的最簡單的事情是擴展Writer並使用日期格式。 應該對其進行優化以僅在需要時打開文件,但是它可以工作。
public class StackOverflowFileRolling extends Writer {
String baseFilePath;
String datePattern;
public StackOverflowFileRolling (String baseFilePath, String datePattern) {
super();
this.baseFilePath = baseFilePath;
this.datePattern = datePattern;
}
@Override
public void write (char[] cbuf, int off, int len) throws IOException {
String name = baseFilePath + new SimpleDateFormat(datePattern).format(new Date()) + ".log";
File file = new File(name);
file.getParentFile().mkdirs();
try (FileWriter fileWriter = new FileWriter(file, true)) {
fileWriter.write(cbuf, off, len);
}
}
@Override
public void flush () throws IOException {
// TODO Auto-generated method stub
}
@Override
public void close () throws IOException {
// TODO Auto-generated method stub
}
}
然后將其包裝在printWriter中使用
try (
PrintWriter logger = new PrintWriter(
new StackOverflowFileRolling("/var/log/stackoverflowfilerolling", "yyyy-MM-dd"))
) {
//this will append 2 lines in the log, since the FileWriter is in append mode
logger.println("test");
logger.println("test2");
}
編輯一些改進以創建目錄並使用PrintWriter
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.