Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change log entry pattern dynamically on some condition

Tags:

java

logback

In my Java app Logback is used as logging framework. The appenders configured with the following pattern (simplified):

[CORR=%X{CORR}] [MSG=%msg]%n

As one can see, CORR value is taken from MDC. Log entry example:

[CORR=12342314] [MSG=Some message]

There are cases when the attribute is not stored in MDC, so log entry looks like:

[CORR=] [MSG=Some message]

But should be:

[MSG=Some message]

Is there any way to totally get rid of this [CORR=] part of pattern if the corresponding value is absent in MDC without creating custom LayoutBase implementations? I'm trying to configure evaluator:

<evaluator name="DISPLAY_CORR_EVAL">
    <expression>((String) mdc.get("CORR")) != null</expression>
</evaluator>

but have no idea how to use it in my case.

like image 971
Aliaxander Avatar asked Aug 31 '26 05:08

Aliaxander


1 Answers

The problem was solved with help of Logback replace(p){r, t} conversion word:

Replaces occurrences of 'r', a regex, with its replacement 't' in the string produces by the sub-pattern 'p'. For example, "%replace(%msg){'\s', ''}" will remove all spaces contained in the event message.

The pattern 'p' can be arbitrarily complex and in particular can contain multiple conversion keywords. For instance, "%replace(%logger %msg){'.', '/'}" will replace all dots in the logger or the message of the event with a forward slash.

My pattern now looks as follows:

%replace([CORR=%X{CORR}]){'\[CORR=\]', ''}[MSG=]%n

when CORR is empty, [CORR=] matches r regex and thus being replaced by empty string.

like image 91
Aliaxander Avatar answered Sep 02 '26 08:09

Aliaxander



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!