Logback pattern equivalent of log4j %l

2019-08-08 01:46发布

Configuring log4j I can use the log4j 1.2 pattern %l to give me location of the caller, which outputs:

... com.example.FooBar.doSomething(FooBar.java:123) ...

I'm trying to switch to Logger because it is "intended as a successor" to log4j and has all sorts of improvements over log4j 1.2

But Logback has no %l pattern. The closest Logback pattern I can find is %caller{1}, but that gives me something ugly:

... Caller+0     at com.example.FooBar.doSomething(FooBar.java:123)
...

Notice that, adding insult to ugly, it adds a newline in the middle of my log line. (I did not specify a newline in the pattern at that point.)

How do I get the equivalent of log4j %l in my Logback pattern?

4条回答
啃猪蹄的小仙女
2楼-- · 2019-08-08 02:23

You can extend the CallerDataConverter and override the convert to strip of the line separator. PatternLayout exposes a static map of converters. You can update this map with your converter as part of bootstrap, better to do in some class initialization static block. Not beautiful but should work.

查看更多
女痞
3楼-- · 2019-08-08 02:30

Another option is to use the replace conversion word. The following regex removes the unwanted Caller and extra new line:

%replace(%caller{1}){'Caller\+0\s*at\s*([^\n]*)\n', '$1'}
查看更多
做个烂人
4楼-- · 2019-08-08 02:44

As durron597 indicated, a single conversion variable that is the exact replacement for log4j %l does not seem to be available. But by combining several conversion variables one can achieve the same effect.

Specifically replace every instance of %l in your log4j configuration with the following for Logback: %class.%method\(%file:%line\)

(If you are doing this programmatically, make sure to double the backslashes as required for Java strings.)

Several of these variables are indicated as degrading the performance of the application. I've looked at the source code, though, and at least the relevant information is cached so that using multiple slow conversion variables in the pattern should not be any worse performance than using just one.

查看更多
Lonely孤独者°
5楼-- · 2019-08-08 02:47

You are correct that %l no longer exists in logback. This is probably because, from your own documentation link:

The location information can be very useful. However, its generation is extremely slow and should be avoided unless execution speed is not an issue.

Unfortunately, you can't do much better with %caller, even though you are correct that it is the best substitute for %l. As you can see in the source here, that newline is pretty thoroughly embedded in the error message generation step.

I wish I had better news for you, but I don't think you're going to be able to do better without a custom Layout. You can take some small comfort in the fact that this has been asked before.


I have just submitted a new Feature Request here.

查看更多
登录 后发表回答