4

I am trying to use logback's replace feature to not have empty values printed in my MDC log pattern. http://logback.qos.ch/manual/layouts.html#replace

I am trying to follow an example from here http://logogin.blogspot.com/2013/04/logback-mdc-and-empty-values.html

Some background

For 90% of the time my log pattern prints

2014-08-28 11:30:27,014  emp:Peter org:IT Expense submitted

For 5% of the time it prints

2014-08-28 11:30:27,014  emp: org: Cleanup jobs.

This is because the emp and org do not need to be supplied on MDC in the latter case. For these cases, I want the emp: and org: to not be present at all in the log line.

Desired

2014-08-28 11:30:27,014  Cleanup jobs.

Possible solution with replace

Here is my variable and the appender I am using. The idea is that the mdcPattern will resolve to an empty string for no emp and org values.

<variable scope="context" name="mdcPattern" value="%replace( emp:%X{empName} org:%X{orgName} ) {'[a-z]+:( |$)', ''}"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%d ${mdcPattern} %thread %-5level %logger{25} - %msg%n</pattern>
    </encoder>
</appender>

However the replace regex does not work. I see log lines as:

2014-08-28 11:30:27,014  emp: org: {'[a-z]+:( |$

My regex is a bit weak. I can't seem to understand why the replace pattern is appearing as is in my log line. Any help is greatly appreciated.

1 Answer 1

5

With help from the author of the original blog post, I've managed to get this to work. He has provided another example on GitHub. http://logogin.blogspot.com/2013/04/logback-mdc-and-empty-values.html

https://gist.github.com/logogin/ff44c254f655340b653c

I had extra spaces in the replacement pattern which I've removed.

Eg: {orgName} ) {'[a-z]+ To: {orgName}){'[a-z]+

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.