我想要 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
?
最佳答案
在您的示例中,调用的是 LogingToFile.doSth
而不是 Bar.doSth
。修改您的配置文件以包括:
myApp.LogingToFile.handlers = java.util.logging.ConsoleHandler
myApp.LogingToFile.useParentHandlers = false
myApp.LogingToFile.level = INFO
或者将 new Bar().doSth();
添加到您的 main 方法中。
通读LogManager
源代码,似乎只有在设置配置后创建记录器时才加载Handlers
。这是错误JDK-8033661
readConfiguration does not cleanly reinitialize the logging system 。列出的解决方法是:
- Do not use per-logger handlers in your log configuration file
- Do not call readConfiguration() or readConfiguration(InputStream), but store the configuration in a file and load it on JVM startup
- Configure your logging through API calls
考虑到您的限制,解决方法是在创建记录器之前加载配置。
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();
}
}
关于java - 通过全局配置文件配置 Logger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24909522/