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

java.util.logging在WSL环境下路径含空格时无日志输出问题求解

问题原因

ClassLoader.getResource()返回的URL对象的getFile()方法会返回URL编码后的路径字符串,路径中的空格会被转换为%20。直接将该字符串作为本地文件路径传给java.util.logging.config.file系统属性时,操作系统无法识别%20编码,导致找不到logging.properties配置文件。Java Util Logging加载配置失败时会静默使用默认配置,因此没有日志输出。

解决方案

以下三种方案均可解决问题,推荐优先使用方案1:

方案1:直接读取资源输入流加载配置(最优)

跳过文件路径解析步骤,直接读取配置文件的输入流传给日志管理器,兼容文件系统、jar包等所有资源加载场景:

package foo;
import java.util.logging.Logger;
import java.util.logging.LogManager;

public class Foo {
    public static void main(String[] args) throws Exception {
        LogManager.getLogManager().readConfiguration(Foo.class.getClassLoader().getResourceAsStream("logging.properties"));
        var l = Logger.getLogger(Foo.class.getName());
        l.info("HOLA!");
    }
}

方案2:通过URI转换获取正确的本地路径

将URL转换为URI后再解析为本地文件路径,自动处理编码转义:

package foo;
import java.net.URI;
import java.nio.file.Paths;
import java.util.logging.Logger;

public class Foo {
    public static void main(String[] args) throws Exception {
        URI logConfigUri = Foo.class.getClassLoader().getResource("logging.properties").toURI();
        String logConfigPath = Paths.get(logConfigUri).toString();
        System.setProperty("java.util.logging.config.file", logConfigPath);
        var l = Logger.getLogger(Foo.class.getName());
        l.info("HOLA!");
    }
}

方案3:解码URL编码的路径

对getFile()返回的编码字符串进行URL解码:

package foo;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

public class Foo {
    public static void main(String[] args) {
        var encodedPath = Foo.class.getClassLoader().getResource("logging.properties").getFile();
        var logConfigPath = URLDecoder.decode(encodedPath, StandardCharsets.UTF_8);
        System.setProperty("java.util.logging.config.file", logConfigPath);
        var l = Logger.getLogger(Foo.class.getName());
        l.info("HOLA!");
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:36:03