springboot如何将控制台的输出保存到文件中

a painting of a blue and yellow flower

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* 控制台日志写入文件
* @author Mr peng
*
*/
@Component
public class ConsoleLogWrite extends OutputStream{

//window输出文件路径
@Value("${consoleLogWrite.windowsUrl}")
private String consoleLogWriteWindowsUrl;
//linux输出文件路径
@Value("${consoleLogWrite.linuxUrl}")
private String consoleLogWriteLinuxUrl;

private OutputStream oldOutputStream, newOutputStream;

public ConsoleLogWrite() {

}

public ConsoleLogWrite(OutputStream oldOutputStream, OutputStream newOutputStream) {
this.oldOutputStream = oldOutputStream;
this.newOutputStream = newOutputStream;
}

//重写输出流的方式,改为两种,一种控制台输出,一种写入指定文件
@Override
public void write(int b) throws IOException {
oldOutputStream.write(b);
newOutputStream.write(b);
}

//当前bean初始化前调用
@PostConstruct
public void writeLogToFile() throws Exception {
File tmplLogFile = new File(getUploadPath(consoleLogWriteLinuxUrl, consoleLogWriteWindowsUrl));
//启一个定时线程延迟15分钟后每过30分钟检查文件大小是否超过100M,如果超过则删除重新创建
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
//文件不存在就创建
if (!tmplLogFile.exists()) {
try {
tmplLogFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//文件大于100M就删除,重新创建
double KB = 1024 * 1024;
double MB = KB * 1024;
if(tmplLogFile.length() > MB * 100){
tmplLogFile.delete();
}
}catch (Exception e) {
e.printStackTrace();
}
}
}, 15, 30, TimeUnit.MINUTES);
//设置输出模式
PrintStream oldOutputStream = System.out;
OutputStream newOutputStream = new FileOutputStream(tmplLogFile);
ConsoleLogWrite multiOutputStream = new ConsoleLogWrite(oldOutputStream, new PrintStream(newOutputStream));
System.setOut(new PrintStream(multiOutputStream));
System.setErr(new PrintStream(multiOutputStream));
}

/**
* 根据当前系统返回对应的路径
* @param linuxPath
* @param windowsPath
* @return
*/
public static String getUploadPath(String linuxPath, String windowsPath) {
if(System.getProperty("os.name").toLowerCase().indexOf("linux") > 0) {
return linuxPath;
}
return windowsPath;
}

}