gamechanger17
gamechanger17

Reputation: 4599

How to remove or replace newline from log messages log4j

I am using below conversion pattern

log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS Z}  [%t] %-5p %c- %m%n

but I want to remove new line characters.

I have tried using %replace(%ex){'[\r\n]+', '\\n'}%nopex%n

but it's not working %replace is not working. it only reading %r and then eplace

Upvotes: 5

Views: 17882

Answers (5)

orcunbalcilar
orcunbalcilar

Reputation: 11

I've found the answer to the original question. The problem is about log4j2 using html entities in replace substitution string. So instead of \n you should use -> 
 So the answer is exactly like below ->

%replace{%msg}{[\r\n]+}{
}

I've spent so much time figuring it out. Finally solved!. I'm sharing for anyone else not wasting the same amount of time. :)

Upvotes: 0

miracle_the_V
miracle_the_V

Reputation: 1156

Replacing is good and all, but there's also a dedicated function for that.

%enc{%m}{CRLF}

Upvotes: 3

RafaelJan
RafaelJan

Reputation: 3608

Warning: May not work for Log4J v1

I also had the same problem, and after investigating it I found that the %replace option is not exist on log4j 1.x.

The link that @Tomasz added for log4j layouts is for log4j 2.x (you can see the version in top of the page on left side).

In addition, from this answer you can understand that not all options from log4j 2.x are available on 1.x

Upvotes: 2

Arvind
Arvind

Reputation: 13

Alternative to @Tomasz Linkowski suggestion is to add the new line at the end

%replace{%msg}{[\r\n]}{}%n

Upvotes: 0

Tomasz Linkowski
Tomasz Linkowski

Reputation: 4496

It seems you were not using the right syntax of the %replace - see Log4j Layouts for the right one.

Using the right syntax, you could remove all the newlines using the following expression:

%replace{%msg}{[\r\n]+}{}

However, removing newlines altogether can make the log hard to read in certain cases. I would suggest that, instead of removing, you replace the newlines with something, e.g. with such an arrow character: ↵ (I chose it for its similarity with the symbol on the Enter key).

So I would suggest using such a pattern:

%replace{%msg}{\r?\n}{↵}

Upvotes: 6

Related Questions