Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logback replace regex to detect empty values

Tags:

regex

logback

mdc

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.

like image 439
Prakash Shankor Avatar asked Oct 28 '25 13:10

Prakash Shankor


1 Answers

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]+

like image 195
Prakash Shankor Avatar answered Oct 30 '25 11:10

Prakash Shankor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!