Chr*_*lma 13 java logging netbeans jar maven
这与其他问题类似,虽然我已经把它logging.properties
放在可执行jar中并且不起作用.
我有一个类(ReportGenerator)具有以下内容:
Logger logger = Logger.getLogger(ReportGenerator.class.getName());
logger.log(Level.INFO, "LOG THIS");
Run Code Online (Sandbox Code Playgroud)
我正在使用Netbeans,所以我将logging.properties
文件放在路径中src/main/resources
.它有(除其他外):
# default file output is in user's home directory.
java.util.logging.FileHandler.pattern = /my/folder/reports.log
java.util.logging.FileHandler.limit = 50000
java.util.logging.FileHandler.count = 10
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter
# Limit the message that are printed on the console to INFO and above.
java.util.logging.ConsoleHandler.level = OFF
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
############################################################
# Facility specific properties.
# Provides extra control for each logger.
############################################################
# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
com.mypackage.ReportGenerator.level = ALL
Run Code Online (Sandbox Code Playgroud)
jar是使用Maven生成的,当解压缩时我可以看到它logging.properties
在jar的主文件夹中.和com
我班级的文件夹一起.
-com
-mypackage
-ReportGenerator
logging.properties
...other things
Run Code Online (Sandbox Code Playgroud)
当我从控制台运行时:
java - jar MyReportsJar.jar
Run Code Online (Sandbox Code Playgroud)
它通过控制台显示日志.我想将它记录到我在中设置的文件中logging.properties.
我究竟做错了什么?如何在不设置JVM java.util.logging.config.file
参数的情况下执行此操作?
Chr*_*lma 14
经过几天的反对并阅读互联网上的许多资源后,我提出了这个解决方案:
我必须在程序中更改LogManager的日志记录属性.我可以使用这样logging.properties
打包的文件.jar
:
LogManager.getLogManager().readConfiguration(ReportGenerator.class.getClassLoader().getResourceAsStream("logging.properties"));
Run Code Online (Sandbox Code Playgroud)
然后我可以像以前一样获取记录器和日志:
Logger logger = Logger.getLogger(ReportGenerator.class.getName());
logger.log(Level.INFO, "LOG THIS");
Run Code Online (Sandbox Code Playgroud)
但我发现你可以logging.properties
在运行时指定另一个文件非常有用所以我的最终代码是这样的:
String logFile = System.getProperty("java.util.logging.config.file");
if(logFile == null){
LogManager.getLogManager().readConfiguration(ReportGenerator.class.getClassLoader().getResourceAsStream("logging.properties"));
}
Logger logger = Logger.getLogger(ReportGenerator.class.getName());
logger.log(Level.INFO, "LOG THIS");
Run Code Online (Sandbox Code Playgroud)
这样,如果我执行jar这样:
java -jar MyReportsJar.jar
Run Code Online (Sandbox Code Playgroud)
它使用内部logging.properties
文件.
但是如果我执行:
java -Djava.util.logging.config.file=<external-logging.properties> -jar MyReportsJar.jar
Run Code Online (Sandbox Code Playgroud)
它使用外部logging.properties
文件.
归档时间: |
|
查看次数: |
11673 次 |
最近记录: |