2014-09-05 68 views
3

我創建了一個命令行工具,該工具作爲可執行jar發佈。當有人使用我的工具時,我不知道罐子的位置。所有的日誌都是通過logback完成的。我希望我的日誌文件和jar文件一樣到達同一個目錄,不管jar的位置在哪裏,也不管當前目錄是什麼。創建時在相同目錄中創建的Logback日誌

我目前的logback.xml文件看起來像這樣。

<configuration> 
    <appender name="FILE" class="ch.qos.logback.core.FileAppender"> 
     <file>admintool.log</file> 
     <encoder> 
      <charset>UTF-8</charset> 
      <pattern>%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"} [%thread] %-5level %logger{35} - %msg %n</pattern> 
     </encoder> 
    </appender> 

    <root level="debug"> 
     <appender-ref ref="FILE" /> 
    </root> 
</configuration> 

有沒有人知道我可以如何讓日誌去罐子的地方?提前致謝。

+0

您是否嘗試從'/ admintool.log'刪除斜線? – ponomandr 2014-09-05 19:48:07

+0

是的,它仍將它放在當前目錄中。 – user3108671 2014-09-05 19:50:52

+0

我認爲你應該考慮在運行時配置logback。請參閱http://stackoverflow.com/questions/5448673/slf4j-logback-how-to-configure-loggers-in-runtime – ponomandr 2014-09-05 19:54:33

回答

2

有一種方法可以提供屬性值,在運行過程中的logback配置:

http://logback.qos.ch/manual/configuration.html#definingPropsOnTheFly

你需要創建一個實現PropertyDefiner接口,並返回jar

public class MyPropertyDefiner extends PropertyDefinerBase { 
    @Override 
    public String getPropertyValue() { 
     return MyPropertyDefiner.class.getProtectionDomain().getCodeSource().getLocation().getFile(); 
    } 
} 

的位置,一類在你的logback.xml中你可以指定類似這樣的東西

<configuration> 
    <define name="jarLocation" class="MyPropertyDefiner"/> 
    <appender name="FILE" class="ch.qos.logback.core.FileAppender"> 
     <file>${jarLocation}</file> 
     ... 
    </appender> 
    ... 
</configuration> 
+0

當我這樣做時,getFile()方法找不到。還有什麼我需要包括? – user3108671 2014-09-05 20:51:45

+0

它應該是getPath()或getFile()。我糾正了答案 – ponomandr 2014-09-05 21:00:51