簡體   English   中英

Java EE 應用程序中的外部 Log4J2 配置

[英]External Log4J2 configuration in Java EE application

我正在開發一個 Java EE 項目,該項目在resources文件夾中有配置文件。 web 項目使用 Maven 組裝成一個 war 文件並部署到 Tomcat。

然后我開始做一些維護,並嘗試在一定程度上將已經成功的配置外部化。

如果您想知道在我編輯代碼之前它是如何生產的,這里是:

// x stands for `application.conf` or  `en.properties` depending on where in the code the file is being 
getClass().getClassLoader().getResourceAsStream(x)

我已將resources下的每個文件移動到/CATALINA_BASE/conf/myProject並且我正在從代碼中的這些路徑中讀取。 (對我來說看起來不是一個好習慣)

這是我的版本:

// x stands for `application.conf` or  `en.properties` depending on where in the code the file is being read
new File(System.getProperty("catalina.base") + "/conf/myProject/x")

這顯然可以正常工作,但是該項目還有一個log4j2.properties文件,該文件之前是從類路徑中自動讀取的,並且由於我已將配置外部化,因此無法從中讀取。

我嘗試的是在web.xml中設置一個參數,如下所示(不確定這樣做是否正確)

<web-app>
...
    <context-param>
<!--        also tried with log4jConfigLocation-->
        <param-name>log4Configuration</param-name>
        <param-value>file:${catalina.base}/conf/myProject/log42.properties</param-value>
    </context-param>
...
</web-app>

應用啟動時出現錯誤output:

錯誤 StatusLogger 找不到 log4j2 配置文件。 使用默認配置:僅將錯誤記錄到控制台。 將系統屬性 'org.apache.logging.log4j.simplelog.StatusLogger.level' 設置為 TRACE 以顯示 Log4j2 內部初始化日志記錄。

SLF4J:無法加載 class “org.slf4j.impl.StaticLoggerBinder”。

SLF4J:默認為無操作(NOP)記錄器實現

任何建議,將不勝感激。

UPDATE: The tomcat running on the server is serving several other applications so setting VM arguments is not an option for me since other projects might have their log4j configurations in their classpath and VM arguments may break those configurations.

您應該 go 到 Catalina.properties 並將 conf/myProject 目錄添加到類路徑。 然后您可以只在類路徑的根目錄中查找文件。 You can create a logging configuration for each web app in that directory by changing your configuration in web.xml to just the name of the file - ie log4j2-appname.xml.

另一種可行的方法是將文件 url 從 file: 更改為 file://。

順便說一句 - 我的雇主有這樣運行的應用程序 - 單個 tomcat 中有多個應用程序。 隨着時間的推移,它已經引起了各種各樣的問題,這確實是一個壞主意。

如果有人遇到這個問題,我已經找到了解決方案。

在深入研究了org.apache.logging.log4j:log4j-core:2.8.2的源文件后,我看到ConfigurationFactory PropertiesUtil.getProperties()的源文件如下所示:

private static final PropertiesUtil LOG4J_PROPERTIES = new PropertiesUtil("log4j2.component.properties");

因此,我在src/main/resources/下創建了一個log4j2.component.properties文件,它只有一行屬性:

log4j.configurationFile=myCustomPath/log4j2.properties

由於我們不能使用logging.config屬性在 Java EE 應用程序中設置配置路徑,這與 Spring 項目不同,因此添加此特定文件解決了我將 log4j 配置外部化的問題。

希望這個答案也對其他人有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM