如何从命令行参数设置 java.util.logging.ConsoleHandler.level?

How to set java.util.logging.ConsoleHandler.level from command line arguments?

当前默认的全局日志记录级别在 JRE_HOME/lib/logging.properties 文件中设置为 INFO

我 运行 从命令行覆盖以下内容并将级别设置为 FINE:

mvn test -Dtest=ABC -Djava.util.logging.ConsoleHandler.level=FINE

而且,我在我的代码中使用以下内容:

logger.fine("Logging works for fine");

上面的消息没有打印在输出中。

如果我将其更改为以下行,则打印成功。

logger.info("Logging works for fine");

我错过了什么?

命令开关 -Djava.util.logging.ConsoleHandler.level=FINE 只是添加了一个 system property 条目。这不被日志记录 API.

使用或读取

相反,所有日志记录属性都由 LogManager 管理。 这是一个独立的程序,向您展示 LogManager 如何更改设置:

public class LogManagerTest {

    public static void main(String[] arg) throws IOException {
        read(LogManager.getLogManager(), create());
        Handler h = new ConsoleHandler();
        System.out.println(h.getLevel());
        h.close();
    }

    private static Properties create() {
        Properties props = new Properties();
        props.setProperty("java.util.logging.ConsoleHandler.level", 
                "FINE");
        return props;
    }

    private static void read(LogManager manager, Properties props) throws IOException {
        final ByteArrayOutputStream out = new ByteArrayOutputStream(512);
        props.store(out, "No comment");
        manager.readConfiguration(new ByteArrayInputStream(out.toByteArray()));
    }
}

就像@Andreas 指出的那样,您将使用调整后的参数创建一个新的属性文件,set the system propertyLogManager 使用具有您所需设置的新属性文件。

添加到: if you are using java-9 or later, then a much easier way to override LogManager's property, is to use LogManager.updateConfiguration(mapper)方法。
所以在ConsoleHandler的等级情况下:

final var propertyName = "java.util.logging.ConsoleHandler.level";
var cmdLineVal = System.getProperty(propertyName);
if (cmdLineVal != null) {
    LogManager.getLogManager().updateConfiguration(
            (key) -> (oldVal, newVal) ->
                    key.equals(propertyName) ? cmdLineVal : newVal);
}

请注意,您不能使用 updateConfiguration(...) 添加新属性:只能修改现有属性。

更新: 我刚刚编写了一个简单的函数来更轻松地对日志配置进行临时命令行更改:overrideLogLevels
您甚至不需要将包含 java-utils 作为项目的依赖项包含在内:只需在启动应用程序时将其添加到您的类路径(在 central 中可用)并定义所需的系统属性:

java -cp /path/to/java-utils.jar:${CLASSPATH} \
-Djava.util.logging.config.class=pl.morgwai.base.logging.JulConfig \
-Djava.util.logging.overrideLevel=,java.util.logging.ConsoleHandler \
-D.level=FINE \
-Djava.util.logging.ConsoleHandler.level=FINE \
${MY_JAVA_APP_MAINCLASS_AND_ARGUMENTS}