我有一个 Java 8 Maven webapp 项目,正在使用 jetty-runner.jar
运行。一切工作正常,除了我无法控制日志记录级别(信息、警告、精细、精细等)。我正在使用 java.util.logging
操作系统为Win7。
我尝试过以下方法:
- 创建了
logging.properties
文件在src/main/resources
文件夹(最终位于WEB-INF/classes
的war
目录中)。 - 已更名
logging.properties
至jetty-logging.properties
- 二手
-Djava.util.logging.config.file=WEB-INF/classes/logging.properties
(当文件如此命名时)使用命令运行jetty-runner
-
java -Djava.util.logging.config.file=WEB-INF/classes/logging.prop erties -jar target/dependency/jetty-runner.jar target/xyz.war
-
- 也尝试过
-Djava.util.logging.config.file=/WEB-INF/classes/logging.properties
(/
位于WEB-INF
前面)
我的日志文件很简单:
.level = WARNING
我之前没有过多地处理日志记录(除了 GAE 项目),所以不确定我做错了什么。
最佳答案
因为您正在尝试从inside of the WAR file加载logging.properties
你必须使用java.util.logging.config.class 。根据文档:
If the "java.util.logging.config.class" property is set, then the property value is treated as a class name. The given class will be loaded, an object will be instantiated, and that object's constructor is responsible for reading in the initial configuration. (That object may use other system properties to control its configuration.) The alternate configuration class can use readConfiguration(InputStream) to define properties in the LogManager.
使用该属性,您可以使用 Class.getResourceAsStream找到 WAR 文件中的文件。这是一个例子:
package foo.bar.baz;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.LogManager;
public class JulConfig {
/**
* Install this as the -Djava.util.logging.config.class=foo.bar.baz.JulConfig
* -Djava.util.logging.config.file=WEB-INF/classes/logging.properties
* @throws Exception if there is a problem.
*/
public JulConfig() throws Exception {
String key = "java.util.logging.config.file";
String file = System.getProperty(key, "logging.properties");
final InputStream in = JulConfig.class.getResourceAsStream(file);
if (in != null) {
try {
LogManager.getLogManager().readConfiguration(in);
//System.clearProperty(key); //Optional.
} finally {
try {
in.close();
} catch (IOException ignore) {
}
}
} else {
throw new FileNotFoundException(file);
}
}
}
您必须这样做的原因是 LogManager uses java.io.File找到logging.properties。
关于java - 使用jetty-runner时无法控制日志记录级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37319636/