在 Java 中,如何在日志文件中包含动态版本信息?
我可以使用自定义日志记录框架从 Java 应用程序记录字符串,如下所示:
logger.info("Version 1.2 of the application is currently running");
因此,当用户向我发送日志文件时,我可以轻松查看他们正在运行的应用程序版本。
上面代码的问题在于版本是硬编码在字符串文字中的,需要有人记住为每个版本更新它。 在发布时忘记更新此字符串是相当不可避免的。
我想做的是根据应用程序 JAR 的清单文件中的版本号之一自动更新此字符串文字:
Specification-Version: 1.2
Implementation-Version: 1.2.0.0
我不介意这种情况是在编译时还是在运行时发生,只要版本号获取到日志文件中。
From a Java application I can log a string, using a custom logging framework, as follows:
logger.info("Version 1.2 of the application is currently running");
Therefore when a user sends me a log file I can easily see what version of the application they are running.
The problem with the code above is that the version is hardcoded in the string literal and someone needs to remember to update it for every release. It's fairly inevitable that updating this string could be forgotten for a release.
What I would like to do is have this string literal automatically updated based on one of the version numbers in the manifest file for the application's JAR:
Specification-Version: 1.2
Implementation-Version: 1.2.0.0
I don't mind if this happens at compile time or at runtime as long as the version number gets into the log file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
获取该信息的标准方法是
SomeClass。
类
。
getPackage()
.
getImplementationVersion()
。您无需自行进行任何解析。
The standard way to get that information is
SomeClass.
class
.
getPackage()
.
getImplementationVersion()
.There's no need to do any parsing on your own.
您可以使用以下类在运行时加载清单,
解析清单中的数据(未经测试)
,然后将解析后的版本包含在日志语句中,
请参阅 Jar 文件规范 了解更多详细信息。
You can load the manifest at runtime using the following class
parse the data from the manifest ( untested )
and then include the parsed version in the log statement
See the Jar file specification for more details.
因此您可以使用 ClassLoader 在运行时加载 /META-INF/MANIFEST。 然后加载并解析
Implementation-Version
:so you can load your /META-INF/MANIFEST at runtime, using the ClassLoader. Then load and parse
Implementation-Version
: