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?
You can extend the
CallerDataConverter
and override theconvert
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.Another option is to use the replace conversion word. The following regex removes the unwanted Caller and extra new line:
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.
You are correct that
%l
no longer exists in logback. This is probably because, from your own documentation link: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.