[英]Find log file name at run time with Java 9 JDK Logging
除了要使用Java 9支持的API之外,我的问题与使用JDK Logging查找实际打开的日志文件相同。
在Java 8中,我目前使用与该问题答案中所述几乎相同的反射技巧,只是我查看实际的日志文件名而不是解析lockFileName。
这是我的代码:
private static String logFileName = null;
public static String getLogFileName() {
// determined on demand and cached so we only need to do all of this the first time.
if (logFileName == null) {
for (Handler handler : Logger.getLogger("").getHandlers()) {
if (handler.getClass().isAssignableFrom(FileHandler.class)) {
FileHandler fileHandler = (FileHandler) handler;
try {
// FileHandler.files has private access,
// so I'm going to resort to reflection to get the file name.
Field privateFilesField = fileHandler.getClass().getDeclaredField("files");
privateFilesField.setAccessible(true); // allow access to this private field
File[] files = (File[]) privateFilesField.get(fileHandler);
logFileName = files[0].getCanonicalPath();
break;
} catch (NullPointerException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | IOException ex) {
logger.log(Level.SEVERE, "Unable to determine log file name.", ex);
}
}
}
if (logFileName == null) {
logFileName = "your home directory"; // just be sure it's not null
logger.warning("Unable to identify log file name.");
}
}
return logFileName;
}
反射hack在Java 8和9中都可以正常工作,但是在Java 9中,它会生成以下警告,我更喜欢使用--illegal-access = permit标志修复该警告,而不是忽略它。
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.foo.MyApp (file:/C:/Users/me/Documents/foo/build/classes/java/main/) to field java.util.logging.FileHandler.files
WARNING: Please consider reporting this to the maintainers of org.foo.MyApp
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
有任何想法吗? 谢谢。
如果特定于Linux的解决方案足够好,您可以尝试解析/proc/self/fd/
的伪符号链接,其中之一应该是当前打开的日志文件,与日志文件模式匹配。
做这件事有很多种方法:
protected
以便您可以在子类中读取它)。 FileHandler
来访问该字段。 同时,您还可以添加代码以迭代所有追加程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.