使用场景
服务器日志文件非常大,不同的线程打印在一个文件里,排查问题非常不方便。log4j好像不支持按线程打印日志的方法,可以通过脚本分割日志。
基本思路
- 读取日志大文件
- 逐行分析日志,根据关键字判断线程名称(比如:pool thread)
- 根据线程名称把内容写入对应的文件
关键代码
环境
jdk 1.8
ide idea
代码
LogService.java
{
private String source;
private String targetPath;
/**
* 线程名称规则, 可以根据实际情况调整
*/
private String[] threadNameRules = {
"pool", "thread"};
private static Map<String, LogHandler> map = new HashMap<>();
public LogService(String source, String targetPath) {
this.source = source;
this.targetPath = targetPath;
}
/**
* 初始化文件夹
*/
private void initFolder() {
File resources = new File(targetPath);
if (resources.exists()) {
/*清空文件夹*/
FileUtils.deleteFile(resources);
} else {
boolean result = resources.mkdir();
if (!result) {
System.out.println("创建文件夹失败");
}
}
}
public void invoke() {
initFolder();
readAndWrite()<