【问题标题】:configure Logger via global config file通过全局配置文件配置 Logger
【发布时间】:2014-07-23 11:40:37
【问题描述】:

我想要 1 个配置文件,其中包含有关特定类中的记录器如何/在哪里/什么记录器应该记录的信息。

例子:

类Foo

package myApp;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

class Foo {
    static final Logger logger = Logger.getLogger(Foo.class.getName());

    public static void main(String[] args) throws IOException {

        FileInputStream fis =  new FileInputStream("C:\\path\\to\\myApp.log.properties");
        LogManager.getLogManager(). readConfiguration(fis);

        logger.log(Level.INFO, "Msg message");

        Bar obj = new Bar();

        obj.doSth();
}

类栏

package myApp;

import java.util.logging.Level;
import java.util.logging.Logger;

public class Bar {

    static final Logger logger = Logger.getLogger(Bar.class.getName());

    public Bar() {
    }

    public void doSth() {
        logger.log(Level.WARNING, "Msg message");
    }
}

文件 myApp.log.properties

handlers = 
config   =

myApp.Foo.handlers           = java.util.logging.ConsoleHandler
myApp.Foo.useParentHandlers  = false
myApp.Foo.level              = INFO

myApp.Bar.handlers           = java.util.logging.ConsoleHandler
myApp.Bar.useParentHandlers  = false
myApp.Bar.level              = INFO

输出:

Jul 23, 2014 1:27:12 PM myApp.Bar doSth
WARNING: Msg message

如您所见,Foo 的日志记录丢失了,我猜这是因为 logger 是静态的,并且是在加载和设置 LogManager 的配置之前创建的。

您能否建议为 Foo 的记录器打印日志记录的解决方案?还带有静态记录器并且没有在程序执行时使用命令行参数-D configFile

【问题讨论】:

标签: java logging


【解决方案1】:

在您的示例中,调用 LogingToFile.doSth 而不是 Bar.doSth。修改您的配置文件以包含:

myApp.LogingToFile.handlers           = java.util.logging.ConsoleHandler
myApp.LogingToFile.useParentHandlers  = false
myApp.LogingToFile.level              = INFO

或将new Bar().doSth(); 添加到您的主方法中。

阅读LogManager 源代码,似乎Handlers 仅在设置配置后创建记录器时才加载。这是错误JDK-8033661 readConfiguration does not cleanly reinitialize the logging system。列出的解决方法是:

  • 不要在日志配置文件中使用每个记录器的处理程序
  • 不要调用 readConfiguration() 或 readConfiguration(InputStream),而是将配置存储在一个文件中,并在 JVM 启动时加载它
  • 通过 API 调用配置您的日志记录

鉴于您的限制,解决方法是在创建记录器之前加载配置。

class Foo {

    static {
        try (FileInputStream fis = new FileInputStream("C:\\path\\to\\myApp.log.properties")) {
            LogManager.getLogManager().readConfiguration(fis);
        } catch (IOException ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    static final Logger logger = Logger.getLogger(Foo.class.getName());

    public static void main(String[] args) throws IOException {
        logger.log(Level.INFO, "Msg message");

        Bar obj = new Bar();

        obj.doSth();
    }
}

【讨论】:

  • 对不起,我替换了s/LogingToFile/Bar/g
猜你喜欢
  • 2022-11-24
  • 1970-01-01
  • 2017-11-24
  • 2014-11-18
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多