2009-08-06 57 views
4

從Java應用程序,我可以登錄一個字符串,使用自定義日誌框架,具體如下:在Java中,如何將動態版本信息包含在日誌文件中?

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

因此,當用戶發送我的日誌文件,我可以很容易地看到他們正在運行什麼版本的應用程序。

上述代碼的問題在於版本在字符串文字中硬編碼,有人需要記住爲每個版本更新它。更新此字符串可能會被忘記發佈是相當不可避免的。

我想什麼做的是有這個字符串基於清單文件的版本號爲應用程序的JAR的一個自動更新:

Specification-Version: 1.2 
Implementation-Version: 1.2.0.0 

我不介意,如果這發生在編譯時間或運行時間,只要版本號進入日誌文件即可。

回答

4

標準的方式來獲取信息是SomeClass.class.getPackage().getImplementationVersion()

有沒有必要自己做任何解析。

+0

不知道爲什麼,但這對我而言返回null。我已經在生成的JAR中檢查了清單,並且它具有版本信息。有任何想法嗎? – Iain 2009-08-06 10:17:28

+0

當然,「SomeClass」必須從問題罐中加載。 – 2009-08-06 11:25:14

+0

你能提供一個SSCCE(http://sscce.org/)嗎? – 2009-08-06 11:25:45

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"); 

請參閱the Jar file specification瞭解更多詳情。

+0

小錯誤。資源名稱開始時缺少斜槓。 getClass()。getResourceAsStream(「/ META-INF/MANIFEST.MF」); – Iain 2009-08-06 09:44:35

+0

修好了,謝謝。 – 2009-08-06 09:58:19

+0

其實有些事情可笑。這給了我Java API清單:清單 Iain 2009-08-06 10:09:13

-1

因此您可以使用ClassLoader在運行時加載您的/ META-INF/MANIFEST。然後加載和分析Implementation-Version

String welcome = String.format("Version %s of the application is currently running", 
          implementationVersion); 
logger.info(welcome); 
+0

演示使用ClassLoader的實際代碼示例會更有幫助。如果不知道如何使用ClassLoader,實際的字符串格式命令不是很有用。 – 2016-05-26 15:32:25

相關問題