繁体   English   中英

使用Java 9 JDK Logging在运行时查找日志文件名

[英]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/的伪符号链接,其中之一应该是当前打开的日志文件,与日志文件模式匹配。

做这件事有很多种方法:

  1. 向JDK提交更改请求以允许访问该字段(至少使其protected以便您可以在子类中读取它)。
  2. 解析用于配置附加程序的属性文件。 您将不得不从Java 9代码中复制一些逻辑,但是很可能该代码不会长时间更改(向后兼容)。
  3. 从日志记录API中复制大量代码,以便您可以编写自己的FileHandler来访问该字段。 同时,您还可以添加代码以迭代所有追加程序。
  4. 使用其他日志记录框架。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM