33

I want to write log like:

2014-04-17 11:00:16.408 [http-apr-9090-exec-4] DEBUG package.method(line) - log.

so I config the logback.xml, in the pattern, the config like:

%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M(%line) - %msg%n

Every thing shows ok except the line number, and if i add set like

%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M %line - %msg%n

Then all works. so there must be something wrong with my configuration.
Could anyone help me ? Thanks. I want to display like what I want, and no space between method name and line number.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Awakening
  • 3,615
  • 8
  • 35
  • 51

4 Answers4

56

The Logback manual states

In PatternLayout, parenthesis can be used to group conversion patterns. It follows that the '(' and ')' carry special meaning and need to be escaped if intended to be used as literals. The special nature of parenthesis is further explained below.

[...]

If you need to treat the parenthesis character as a literal, it needs to be escaped by preceding each parenthesis with a backslash. As in, \(%d{HH:mm:ss.SSS} [%thread]\).

You'll need to escape the parenthesis with a \.

%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
5

A note for anyone who stumbles onto this page looking for how to configure this in the application.properties file, I had success escaping the parenthesis by adding two backslashes.

%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M \\(%line\\) - %msg%n
Derek
  • 126
  • 1
  • 7
  • 1
    The added backslash isn't for the parenthesis, it's for the first backslash. – Sotirios Delimanolis Oct 31 '18 at 17:59
  • I was unable to track down why I had to use two backslashes. I agree that's what should be happening. Perhaps one of the frameworks involved demanded the extra backslash. – Derek Feb 08 '19 at 16:33
5

If you want to have log messages where you can click on a link into the source code, e.g. in IntelliJ, use the following pattern for console logging inside your IDE:

<pattern>
    %d{dd-MM-yyyy HH:mm:ss.SSS} %highlight(%-5level) %magenta([%thread]) %yellow(%logger{40}.%M\(%class{0}.java:%line\)) - %msg%throwable%n
</pattern>
Rüdiger Schulz
  • 2,588
  • 3
  • 27
  • 43
1

For console logging I use:

<Pattern>%black(%date{"yyyy-MM-dd HH:mm:ss.SSS", "Europe/London"}) %highlight(%-5level) [%green(%X{sessionId})] %yellow(%logger{36}@%method\(%line\)) - %msg%n%throwable</Pattern>

And for logging to file:

 <pattern>[%date{"yyyy-MM-dd HH:mm:ss,SSSXXX", "Europe/London"}] [${HOSTNAME}] [%thread] %level %logger{36}@%method:%line - %msg%n</pattern>
theINtoy
  • 3,388
  • 2
  • 37
  • 60