MDC is a thread-wide structure. At present time, it cannot be set per logging event. Any changes you make to the mdcPropertyMap (retrieved by calling event.getMDCPropertyMap()) will be visible to all future events generated in the same thread.



On 3/9/2015 21:03, Cemo wrote:
I have a layout which is generating JSON from logging events and MDC
Context. MDC is great and I want to add parameters to MDC Context
conditionally. For example, I would like add request information as JSON
into MDC conditionally on Error Level log entries. I am not familiar
with Logback internals but gave a try with Logback Filter
implementation. I have used:

    public  FilterReply decide(ILoggingEvent event) {

       // simplifiedfor  demo
       // conditionally I am putting some attributes here
       Map<String,String> mdcPropertyMap = event.getMDCPropertyMap();
       if  (event.getLevel().isGreaterOrEqual(Level.ERROR)) {
          mdcPropertyMap.put("demo","demo");
       }
       return  FilterReply.ACCEPT;
    }



I am expecting mdcPropertyMap to be cleared for each event but it does
not. LoggingEvent has a internal CACHED_NULL_MAP map and its modified
per touch.

  private  static  final  Map<String,String> CACHED_NULL_MAP =new  
HashMap<String,String>();


I could not be sure but it seems a little bid buggy to me. Can someone
verify this behaviour?

For those who are interested why I am not using MDC.put in a Servlet
Filter implementation because I am conditionally adding some attributes.
Serialising HttpRequest into JSON is not cheap task but having Http
Request information is giving great insights about error. Using Filter
is the only way I found to add conditionally attributes so far. What I
would like to use is:


    public  FilterReply decide(ILoggingEvent event) {
       if  (event.getLevel().isGreaterOrEqual(Level.WARN)) {
          MDC.put("demo","demo");
       }
       return  FilterReply.ACCEPT;
    }




_______________________________________________
Logback-user mailing list
[email protected]
http://mailman.qos.ch/mailman/listinfo/logback-user

_______________________________________________
Logback-user mailing list
[email protected]
http://mailman.qos.ch/mailman/listinfo/logback-user

Reply via email to