Commit e02082e6e27bbd6b713477b6ef03c3e66311629c
1 parent
24fccca47a
Exists in
master
and in
6 other branches
add log4j async flush disk
Showing 1 changed file with 52 additions and 0 deletions
platform-common/src/main/java/com/lyms/platform/common/log4j/DailyRollingFileAppender.java
View file @
e02082e
1 | +package com.lyms.platform.common.log4j; | |
2 | + | |
3 | +import org.apache.log4j.Layout; | |
4 | +import org.apache.log4j.helpers.QuietWriter; | |
5 | + | |
6 | +import java.io.File; | |
7 | +import java.io.IOException; | |
8 | + | |
9 | +/** | |
10 | + * | |
11 | + * 解决log4j BufferedIO=true 时,buffer有残余日志不能记录的问题 | |
12 | + * | |
13 | + * Created by jiangjiazhi on 2017/5/22. | |
14 | + */ | |
15 | +public class DailyRollingFileAppender extends | |
16 | + org.apache.log4j.DailyRollingFileAppender { | |
17 | + | |
18 | + public DailyRollingFileAppender() { | |
19 | + super(); | |
20 | + Runtime.getRuntime().addShutdownHook(new Log4jHockThread()); | |
21 | + } | |
22 | + | |
23 | + public DailyRollingFileAppender(Layout layout, String filename, | |
24 | + String datePattern) throws IOException { | |
25 | + super(layout, filename, datePattern); | |
26 | + Runtime.getRuntime().addShutdownHook(new Log4jHockThread()); | |
27 | + } | |
28 | + | |
29 | + @Override | |
30 | + public synchronized void setFile(String fileName, boolean append, | |
31 | + boolean bufferedIO, int bufferSize) throws IOException { | |
32 | + File logfile = new File(fileName); | |
33 | + | |
34 | + logfile.getParentFile().mkdirs(); | |
35 | + | |
36 | + super.setFile(fileName, append, bufferedIO, bufferSize); | |
37 | + } | |
38 | + | |
39 | + public QuietWriter getQw() { | |
40 | + return super.qw; | |
41 | + } | |
42 | + | |
43 | + private class Log4jHockThread extends Thread { | |
44 | + @Override | |
45 | + public void run() { | |
46 | + QuietWriter qw = DailyRollingFileAppender.this.getQw(); | |
47 | + if (qw != null) { | |
48 | + qw.flush(); | |
49 | + } | |
50 | + } | |
51 | + } | |
52 | + } |