java - Logback获取方法名称

java - Logback获取方法名称-LMLPHP

摘自: https://blog.csdn.net/qq853632587/article/details/78222780

我们目前正在从 Log4J 迁移到 Logback,但是在获取触发日志的"原"方法名称时遇到了问题。

我叫它"原",因为我们有一个集中的记录器类( 隐藏和操作某些日志) 和日志中显示的方法名称。

在 Log4J 中,我们能够正确获取"原"方法名。

Logback是否能够获得它?

记录器参数:

Log4J

复制代码
<param name="ConversionPattern" value="%d{dd-MM-yyyy HH:mm:ss,SSS} %5p [%F] - %M() - %m%n"/>

Logback

复制代码
<pattern>%d{"dd-MM-yyyy HH:mm:ss,SSS"} %-5level [%logger - %M] - %msg%n</pattern>

结果:( 方法名称- 类名)

Log4J

复制代码
doLogTester1 - a.Tester1  doLogTester2 - b.Tester2  doLogTester1 - a.Tester1  doLogTester2 - b.Tester2 

Logback

复制代码
processLog - a.Tester1  processLog - b.Tester2  processLog - a.Tester1  processLog - b.Tester2 

编辑 - 完整示例

Main.java

复制代码
public class Main { private static final LoggerCommon logger = new LoggerCommon(Main.class); public static void main(String[] args) {  logger.doLog("I'm on the Main class in the main method"); } }

LoggerCommon

log4j

复制代码
import org.apache.log4j.Level; import org.apache.log4j.Logger; public class LoggerCommon { private static Logger logger; public LoggerCommon(Class<?> c) {  logger = Logger.getLogger(c); } public void doLog(String message) {  logger.log(LoggerCommon.class.getName(), Level.INFO, message, null); } }

logback

复制代码
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LoggerCommon { private Logger logger; public LoggerCommon(Class<?> c) {  logger = LoggerFactory.getLogger(c); } public void doLog(String message) {  logger.info(message); } }

config配置

log4j

复制代码
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="CA" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%M - %F - %m%n"/> </layout> </appender> <root> <level value="debug"/> <appender-ref ref="CA"/> </root> </log4j:configuration>

logback

复制代码
<configuration> <appender name="CA" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%M - %logger - %msg %n</pattern> </encoder> </appender> <root level="TRACE"> <appender-ref ref="CA"/> </root> </configuration>
05-12 04:16