在Java中如何开发简单的日志记录工具_Java文件写入项目解析

Java轻量日志工具需用FileWriter(true)追加、BufferedWriter缓冲并显式flush(),synchronized保证线程安全,DateTimeFormatter格式化时间,按天滚动文件,每次写入前检查日期并重开流,关键在及时flush和健壮close。

Java里写个轻量日志工具,不用引入Log4j或SLF4J也能搞定——关键是把 FileWriterBufferedWriter 用对,再加点线程安全和格式控制,就能应付多数本地调试、脚本运行、小型服务的日志需求。

为什么别直接用 FileWriter 单独写日志

单独用 FileWriter 容易丢日志:每次 write() 都触发磁盘 I/O,性能差;没缓冲,异常中断时最后一段内容可能根本没落盘;多线程并发写同一文件会错乱甚至覆盖。

  • 必须套一层 BufferedWriter,启用缓冲并显式调用 flush()
  • 写操作要包裹在 synchronized 块或使用 ReentrantLock,避免多线程交叉写入
  • 构造 FileWriter 时传入 true(即 new FileWriter(file, true)),开启追加模式,否则每次都会清空文件

怎么让日志带时间戳和级别前缀

纯文本日志没人想手动拼接 [2025-06-12 14:23:05][INFO] ——用 SimpleDateFormat 格式化,但注意它不是线程安全的,不能复用同一个实例。

  • 每次写日志都新建 SimpleDateFormat 实例(开销小,可接受)
  • 或改用线程安全的 DateTimeFormatter(Java 8+),例如:DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
  • 级别建议用枚举封装,比如 LogLevel.INFOLogLevel.ERROR,方便后续扩展过滤逻辑

如何避免日志文件无限增长

不加控制的话,几天就生成几十MB的单个日志文件,既难排查又占空间。最简单有效的方案是「按天滚动」。

  • 每次写入前检查当前日志文件名是否匹配今天日期(如 app-2025-06-12.log
  • 不匹配就关闭旧流、重命名旧文件、用新日期创建新 FileWriter
  • 不要依赖文件大小滚动——它需要额外读取统计,且小文件频繁切换反而影响性能
  • 可选:保留最近7天的日志,老文件自动 delete()(注意判断返回值,delete() 可能失败)
public class SimpleLogger {
    private static final String LOG_DIR = "logs";
    private static final String LOG_PATTERN = "app-yyyy-MM-dd.log";
    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    private File currentLogFile;
    private BufferedWriter writer;
    private String currentDay;

    public SimpleLogger() throws IOException {
        init();
    }

    private void init() throws IOException {
        Files.createDirectories(Paths.get(LOG_DIR));
        rotateIfNecessary();
    }

    private void rotateIfNecessary() throws IOException {
        String today = LocalDate.now().toString();
        if (!today.equals(currentDay)) {
            closeWriter();
            currentDay = today;
            String filename = LOG_DIR + "/app-" + currentDay + ".log";
            currentLogFile = new File(filename);
            writer = new BufferedWriter(new FileWriter(currentLogFile, true));
        }
    }

    public void info(String msg) {
        write("INFO", msg);
    }

    public void error(String msg) {
        write("ERROR", msg);
    }

    private void write(String level, String msg) {
        try {
            rotateIfNecessa

ry(); String time = LocalDateTime.now().format(DATE_FORMAT); writer.write(String.format("[%s][%s] %s%n", time, level, msg)); writer.flush(); // 关键:不 flush 可能滞留在缓冲区 } catch (IOException e) { // 此处不能再打日志,避免死循环,仅控制台输出或静默丢弃 System.err.println("Log write failed: " + e.getMessage()); } } private void closeWriter() { if (writer != null) { try { writer.close(); } catch (IOException ignored) {} writer = null; } } }

真正容易被忽略的是 flush() 的调用时机和 closeWriter() 的健壮性——很多简易实现只在程序退出时关流,但进程异常终止(比如 kill -9)会导致最后几条日志永远丢失。如果对可靠性要求高,就得考虑内存队列 + 守护线程定期刷盘,或者直接切到成熟的日志框架。