簡體   English   中英

如何在不執行 log4j2 reconfigure() 的情況下更新 ${ctx:key} 以實現動態文件名

[英]How to update ${ctx:key} to achieve dynamic file name without executing log4j2 reconfigure()

現在我對 log4j2 有疑問。

我的目標是:根據MDC map中“fileName”的值來確定記錄哪個文件。

例如

public class A {
    
    void test() {
        //log in A.log
        MDC.put("fileName", A);
        
        //LoggerContext ctx = (LoggerContext)LoggerContext.getContext(false);
        //ctx.reconfigure();
        
        //Now, I want it log in A.log
        log.info("aaa");
        C c = new C();
        c.test();       
    }
    
}

public class B {
    
    void test() {
        //log in B.log
        MDC.put("fileName", B);
    
        //LoggerContext ctx = (LoggerContext)LoggerContext.getContext(false);
        //ctx.reconfigure();
        //Now, I want it log in B.log
        log.info("bbb");
        C c = new C();
        c.test();
    }

}

public class C {
    
    void test() {
        log.info("cccc");
    }   
    
}   

我的 log4j2.xml 是

<RollingFile name="rollingFile" fileName="/home/logs/${ctx:key}.log"
             filePattern="/home/logs/application-${ctx:key}-i.log">
    <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n"/>
    <Policies>
        <SizeBasedTriggeringPolicy size="2MB"/>
    </Policies>
    <DefaultRolloverStrategy max="10"/>
</RollingFile>

如果我取消注釋 reconfigure(),它會在執行 A.test()、“aaa”、“cccc”時登錄 A.log,在執行 B.test()、“bbb”、“cccc”時登錄 B。日志。

LoggerContext ctx = (LoggerContext)LoggerContext.getContext(false);
ctx.reconfigure();

但是考慮到高並發場景,擔心頻繁更新會造成IO資源等性能問題。

在 log4j2 的配置中,我們可以使用 %X{key} 來實時獲取 MDC map 的值。

那么有沒有可能我們不需要每次MDC map值變化的時候都去執行reconfigure()呢?

或者有什么辦法可以實現我的目標?

你想使用RoutingAppender 你會用它作為

<Routing name="Routing">
  <Routes pattern="$${ctx:fileName}">
    <Route>
      <RollingFile name="rollingFile" fileName="/home/logs/${ctx:fileName}.log"
         filePattern="/home/logs/application-${ctx:fileName}-i.log">
        <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n"/>
        <SizeBasedTriggeringPolicy size="2MB"/>
        <DefaultRolloverStrategy max="10"/>
      </RollingFile>
    </Route>
  <Routes>
<Routing>

請注意,這只會配置默認路由,因此如果未提供文件名,您最終將記錄到一個名為 ${ctx:fileName}-n.log 的文件。

您還需要知道,僅當 fileName 的可能值有限時才應使用它。 但是,如果事先都知道它們,那么直接聲明它們確實更好。 如果 fileName 沒有得到很好的控制,您最終可能會用完文件句柄。

暫無
暫無

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

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