Search code examples
javalogginglog4jlogback

Logback pattern equivalent of log4j %l


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?


Solution

  • 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.