You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java util.logging配置后users.home目录未生成myApp.log日志文件求助

问题根因

你只获取了logging.properties的文件路径,没有将配置加载到java.util.logging的LogManager中,日志系统始终使用默认配置,因此只会输出到控制台,不会生成日志文件。同时存在类加载顺序问题:日志初始化早于配置加载,也会导致配置不生效。


修复方案

1. 完善LoadLogPropertiesFile类,实现配置加载

修改静态代码块,读取配置文件流并加载到日志管理器,代码如下:

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.LogManager;

public class LoadLogPropertiesFile {

    private static LoadLogPropertiesFile instance = new LoadLogPropertiesFile();
    public static LoadLogPropertiesFile getInstance() {
        return instance;
    }

    static {
        System.out.println("Loading log properties file -->");
        try (InputStream inputStream = LoadLogPropertiesFile.class.getClassLoader().getResourceAsStream("logging.properties")) {
            if (inputStream == null) {
                throw new RuntimeException("找不到logging.properties配置文件");
            }
            // 加载配置到日志管理器
            LogManager.getLogManager().readConfiguration(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("加载日志配置失败", e);
        }
    }
}

2. 调整代码执行顺序,保证配置优先加载

你当前的AEvent类中,静态logger初始化早于LoadLogPropertiesFile类加载,需要调整为加载配置后再初始化日志,修改后的AEvent参考如下:

package com.jnlp;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Logger;
class AEvent extends Frame implements ActionListener{

    private static final long serialVersionUID = 1L;
    // 先触发配置加载
    private static final LoadLogPropertiesFile logProp = LoadLogPropertiesFile.getInstance();
    // 配置加载完成后再初始化Logger
    private static Logger logger = Logger.getLogger(LoadLogPropertiesFile.class.getName());
    TextField tf;
    AEvent(){

        //create components
        tf=new TextField();
        tf.setBounds(60,50,170,20);
        Button b=new Button("click me");
        b.setBounds(100,120,80,30);

        //register listener
        b.addActionListener(this);//passing current instance

        //add components and set size, layout and visibility
        add(b);add(tf);
        setSize(300,300);
        setLayout(null);
        setVisible(true);
    }
    public void actionPerformed(ActionEvent e){

    }
    public static void main(String args[]){
        logger.info("Test logging....");
        new AEvent();
    }
}

验证说明

  • 配置中%h对应用户主目录,Windows系统下为C:\Users\你的用户名,macOS/Linux系统下为/Users/你的用户名,确认该目录有写入权限即可正常生成myApp.log文件
  • 运行后先确认控制台输出了Loading log properties file -->日志,说明配置已触发加载

内容的提问来源于stack exchange,提问作者Karthikeyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 05:06:04