贝利信息

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

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

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

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

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

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

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

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

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

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 {
            rotateIfNecessary();
            String time = LocalDateTime.now().format(DATE_FORM

AT); 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)会导致最后几条日志永远丢失。如果对可靠性要求高,就得考虑内存队列 + 守护线程定期刷盘,或者直接切到成熟的日志框架。