Java logback 显示带有行号的日志

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23123934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 20:52:58  来源:igfitidea点击:

logback show logs with line number

javalogginglog4jlogback

提问by Awakening

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:

所以我在模式中配置 logback.xml,配置如下:

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

Every thing shows ok exceptthe 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.

然后一切正常。所以我的配置肯定有问题。
有人可以帮我吗?谢谢。我想像我想要的那样显示,并且方法名称和行号之间没有空格。

采纳答案by Sotirios Delimanolis

The Logback manualstates

的logback手动状态

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]\).

在 PatternLayout 中,括号可用于对转换模式进行分组。因此,'(' 和 ')' 具有特殊含义,如果打算用作文字,则需要对其进行转义。下面进一步解释括号的特殊性质。

[...]

如果您需要将括号字符视为文字,则需要通过在每个括号前加上反斜杠来对其进行转义。如, \(%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

回答by Derek

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.

任何偶然发现此页面以寻找如何在 application.properties 文件中配置它的人的注意事项,我通过添加两个反斜杠成功地转义了括号。

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

回答by theINtoy

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>