簡體   English   中英

log4j2.xml 查找系統屬性由 Spring 設置

[英]log4j2.xml lookup system properties set by Spring

我正在從 log4j 1.x 遷移到 2.x,我們有一個屬性文件“foo.properties”,我們在 spring 的applicationContext.xml中讀取並轉換為系統屬性:

    <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="foo" value="classpath:META-INF/properties/foo.properties" />
    </bean>

    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject">
            <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
                <property name="targetClass" value="java.lang.System" />
                <property name="targetMethod" value="getProperties" />
            </bean>
        </property>
        <property name="targetMethod" value="putAll" />
        <property name="arguments">
            <util:properties>
                <prop key="x.y.z">${x.y.z}</prop>
                <prop key="a.b.c">${a.b.c}</prop>
                ...
        </util:properties>
        </property>
    </bean>

我希望現在能夠像<RollingFile name="rollingFile" fileName="${sys:xyz}">一樣在 log4j2.xml 中引用xyz ,但這不適用於 2.x。 使用 1.x ${xyz}可以正常工作。

之前,我們在applicationContext.xml中有這段代碼來初始化 log4j:

    <bean id="log4jInitialization"
        class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetClass" value="org.springframework.util.Log4jConfigurer" />
        <property name="targetMethod" value="initLogging" />
        <property name="arguments">
            <list>
                <value>classpath:log4jMain.xml</value>
            </list>
        </property>
    </bean>

但這被刪除了,因為它不適用於 2.x,這可能已經破壞了某些東西。 如何讓 log4j2 查找由 Spring 設置的系統屬性?

如果您使用 Spring 啟動 Log4j 將至少初始化 3 次,第一次是在 Spring 執行任何操作之前。 所以 Spring 不可能為您設置這些屬性。 但是,后續調用初始化日志記錄可能能夠提供屬性,但這並不是真正必要的,因為 Log4j 可以為您處理這個問題。

選項 1 - 如果您使用 Spring 引導,則包括 Log4j Spring 雲配置客戶端。 它包含一個 SpringLookup,可讓您引用 Spring 配置中定義的任何屬性。 例如,如果您有一個 application.yaml 包含:

logging:
  root:
    level:

您可以在 log4j2.xml 文件中引用 ${spring:logging.root.level}。

選項 2 - 如果您不使用 Spring 引導或更喜歡系統屬性,那么您可以在類路徑上創建一個名為 log4j2.system.properties 的文件。 在此文件中找到的所有屬性將由 Log4j 在 Log4j 初始化開始時作為系統屬性發布。

暫無
暫無

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

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