2017-08-31 71 views
3

在Logback中,可以使用setLevel()方法更改記錄器的日誌級別。 但是在Logback中,因爲記錄器是singleton,所以setLevel()方法的調用將影響所有其他使用相同記錄器的線程。如何使用Logback更改當前線程的日誌級別

現在我在web應用中使用這樣的類:

class FooService { 
    private void insertRecord(Foo foo) { 
     // insert one record to DB 
    } 

    public void insertOne(Foo foo) { 
     insertRecord(foo); 
    } 

    public void insertMany(List<Foo> foos) { 
     // I want to stop logging here 
     for (Foo foo: foos) { 
      insertRecord(foo); 
     } 
     // I want to resume logging here 
    } 
} 

,春天ApplicationConfig.xml:

<bean id="traceAdvice" 
    class="org.springframework.aop.interceptor.CustomizableTraceInterceptor"> 
    <property name="enterMessage" 
    value="Entering $[targetClassShortName].$[methodName]($[argumentTypes])[$[arguments]]" /> 
    <property name="exitMessage" 
    value="Exiting $[targetClassShortName].$[methodName] : return = $[returnValue] : time = $[invocationTime]ms" /> 
    <property name="exceptionMessage" 
    value="Exception thrown in $[targetClassShortName].$[methodName] : $[exception]" /> 
</bean> 

<aop:config> 
    <aop:pointcut id="pointcut-service" 
    expression="execution(* my.app.service..*Service.*(..))" /> 
    <aop:advisor advice-ref="traceAdvice" pointcut-ref="pointcut-service" /> 
</aop:config> 

我想記錄從insertOne方法insertRecord的調用。另一方面,在insertMany方法中,我希望在循環之前停止日誌記錄(因爲它可能會輸出大量日誌),並在循環之後繼續日誌記錄。 但是,如果在循環之前調用setLevel(),則日誌級別的更改將影響其他線程中使用的其他記錄器。在這種情況下,我認爲你會在其他線程上得到明確的日誌。

我的問題是:如何更改當前線程中使用的記錄器的日誌級別?

+0

您可以定義一個特定的appender你的包或者你 –

+0

類五言,你可以定義更多的appender類FooService接口,但是如果有兩個或更多線程同時執行FooService,則所有線程都會受到setLevel()的影響。這對我來說是不理想的結果。 – satob

回答

2

我找到了解決方案。您可以爲此使用MDC和TurboFilter。 MDC是線程本地的,更改爲MDC不會影響其他線程。

例如,如果要停止所有日誌活動,你必須MDCFilter的定義添加到logback.xml(請注意,<turboFilter>標籤不能是<appender>標籤的孩子,應該是<configuration>標籤的孩子) :

<configuration> 
    <turboFilter class="ch.qos.logback.classic.turbo.MDCFilter"> 
     <MDCKey>tracing</MDCKey> 
     <Value>off</Value> 
     <OnMatch>DENY</OnMatch> 
    </turboFilter> 
    ...... 
</configuration> 

,您可以通過PUT /關閉記錄/刪除鍵,這樣的值MDC(請注意,你應該考慮有關的異常在實際使用中):

class FooService { 
    private void insertRecord(Foo foo) { 
     // insert one record to DB 
    } 

    public void insertOne(Foo foo) { 
     insertRecord(foo); 
    } 

    public void insertMany(List<Foo> foos) { 
     // I want to stop logging here 
     MDC.put("tracing", "off"); 
     for (Foo foo: foos) { 
      insertRecord(foo); 
     } 
     // I want to resume logging here 
     MDC.remove("tracing"); 
    } 
} 

或者,如果你想停止跟蹤/調試/ INFO/WARN日誌,但留下錯誤日誌活躍,您可以使用DynamicThresholdFilter:

<configuration> 
    <turboFilter class="ch.qos.logback.classic.turbo.DynamicThresholdFilter"> 
     <Key>tracing</Key> 
     <DefaultThreshold>TRACE</DefaultThreshold> 
     <MDCValueLevelPair> 
     <value>off</value> 
     <level>ERROR</level> 
     </MDCValueLevelPair> 
    </turboFilter> 
    ...... 
</configuration> 
+0

DynamicThresholdFilter正是我所需要的,謝謝! – xtian

相關問題