JAVA简易日志工具类

JAVA日志输出到文件

PS :

  • 你是否遇到过控制台打印了一堆日志,想找到自己想看的日志,翻了半天发现被顶没了😒
  • 尤其是在多线程环境下,有时候正常使用log日志框架打印的日志还可能被吞掉

小说明

  • 修改包名即可使用
  • 代码中判断了路径,所以简易使用的时候直接传入一个文件名称即可(这样无论是window还是打包发布之后,默认都会生成到当前项目或者当前jar的目录下)
  • 代码中还打印了错误堆栈信息,方便找到错误行

上码

源代码
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

package com.example.demo.util;

import java.io.*;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LogUtils {

private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

/**
* 追加写入异常日志(含堆栈信息)
*
* @param filePath 日志文件路径(支持相对路径和绝对路径)
* @param message 自定义错误说明
* @param throwable 异常对象(可为 null)
*/
public static void appendErrorLog(String filePath, String message, Throwable throwable) {
// 处理相对路径问题,转化为绝对路径
File file = getAbsoluteFile(filePath);

// 保证父目录存在
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}

synchronized (LogUtils.class) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, true))) {
writer.write("============================================================");
writer.newLine();
writer.write("时间: " + DATE_FORMAT.format(LocalDateTime.now()));
writer.newLine();
writer.write("错误信息: " + message);
writer.newLine();

if (throwable != null) {
writer.write("异常类型: " + throwable.getClass().getName());
writer.newLine();
writer.write("异常消息: " + throwable.getMessage());
writer.newLine();
writer.write("堆栈信息:");
writer.newLine();

// 将完整堆栈输出
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
writer.write(sw.toString());
}

writer.newLine();
writer.flush();
} catch (IOException e) {
System.err.println("写入错误日志失败:" + e.getMessage());
}
}
}

/**
* 将相对路径转换为绝对路径
*
* @param filePath 相对路径或绝对路径
* @return 绝对路径的文件
*/
private static File getAbsoluteFile(String filePath) {
File file = new File(filePath);
// 如果是相对路径,则转换为绝对路径
if (!file.isAbsolute()) {
// 获取当前工作目录并转换为绝对路径
String currentDir = System.getProperty("user.dir");
file = new File(currentDir, filePath);
}
return file;
}
}