我有与Find actual opened logfile with JDK Logging相同的问题,除了我想使用Java 9支持的API。
在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;
}
反射黑客在Java 8和Java中都运行良好。 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
有什么想法吗?感谢。
答案 0 :(得分:0)
如果特定于Linux的解决方案足够好,您可以尝试解析/proc/self/fd/
中的伪符号链接,其中一个应该是当前打开的日志文件,与日志文件模式匹配。
答案 1 :(得分:0)
有几种方法可以做到这一点:
protected
,以便您可以在子类中读取它。)FileHandler
,以便访问该字段。在此期间,您还可以添加代码来迭代所有appender。