4

从 Java 应用程序中,我可以使用自定义日志框架记录字符串,如下所示:

logger.info("Version 1.2 of the application is currently running");

因此,当用户向我发送日志文件时,我可以轻松查看他们正在运行的应用程序版本。

上面代码的问题是版本是硬编码在字符串文字中的,有人需要记住为每个版本更新它。更新此字符串可能会被遗忘,这是相当不可避免的。

我想做的是让这个字符串文字根据应用程序 JAR 清单文件中的版本号之一自动更新:

Specification-Version: 1.2
Implementation-Version: 1.2.0.0

只要版本号进入日志文件,我不介意这种情况发生在编译时还是运行时。

4

3 回答 3

4

获取该信息的标准方法是.SomeClass.class.getPackage().getImplementationVersion()

无需自己进行任何解析。

于 2009-08-06T09:46:46.343 回答
0

您可以使用以下类在运行时加载清单

public class ManifestFinder {

    private final Class<?> _theClass;


    public ManifestFinder(Class<?> theClass) {

        _theClass = theClass;
    }


    public Manifest findManifest() throws MalformedURLException, IOException {

        String className = _theClass.getSimpleName();
        String classFileName = className + ".class";
        String pathToThisClass = _theClass.getResource(classFileName).toString();

        int mark = pathToThisClass.indexOf("!");
        String pathToManifest = pathToThisClass.toString().substring(0, mark + 1);
        pathToManifest += "/META-INF/MANIFEST.MF";
        return new Manifest(new URL(pathToManifest).openStream());

    }

}

解析清单中的数据(未经测试)

 String specificationVersion = manifest.getMainAttributes().getValue("Implementation-Version");

然后在日志语句中包含解析的版本

logger.info("Version " + specificationVersion + " of the application is currently running");

有关更多详细信息,请参阅Jar 文件规范

于 2009-08-06T09:30:25.300 回答
-1

因此您可以使用 ClassLoader 在运行时加载 /META-INF/MANIFEST。然后加载并解析Implementation-Version

String welcome = String.format("Version %s of the application is currently running",
                          implementationVersion);
logger.info(welcome);
于 2009-08-06T09:31:58.463 回答