Java-logback Get method name
Excerpt: 78222780
We are currently migrating from log4j to Logback, but we are having trouble getting the "original" method name that triggered the log.
I call it "original" because we have a centralized logger class (hiding and manipulating some logs) and the method name shown in the log.
In log4j, we are able to get the "original" method name correctly.
is logback able to get it?
Logger Parameters :
Log4j
Copy Code
<paramname="ConversionPattern"value="%d{dd-MM-yyyy HH:mm:ss,SSS} %5p [%F] - %M() - %m%n"/>
Logback
Copy Code
<pattern>%d{"dd-MM-yyyy HH:mm:ss,SSS"} %-5level [%logger - %M] - %msg%n</pattern>
Result: (method name-class name)
Log4j
copy code
doLogTester1 - a.Tester1 doLogTester2 - b.Tester2 doLogTester1 - a.Tester1 doLogTester2 - b.Tester2
Logback
copy code
processLog - a.Tester1 processLog - b.Tester2 processLog - a.Tester1 processLog - b.Tester2
Edit -complete Example
Main.java
Copy Code
Public class Main { Private StaticFinalLoggercommonLogger= New Loggercommon(Main.class); Public Static voidMain(String[]args) {Logger.Dolog("I ' m on the main class in the Main method"); } }
Loggercommon
Log4j
Copy Code
Importorg.Apache.log4j. Level; Importorg.Apache.log4j.Logger; Public class Loggercommon { Private Static LoggerLogger; Public Loggercommon(Class<?>C) {Logger= Logger.GetLogger(C); } Public voidDolog(Stringmessage) {Logger.Log(Loggercommon.class.GetName(), Level.INFO,message, NULL); } }
Logback
Copy Code
Importorg.slf4j.Logger; Importorg.slf4j.loggerfactory; Public class Loggercommon { Private LoggerLogger; Public Loggercommon(Class<?>C) {Logger= loggerfactory.GetLogger(C); } Public voidDolog(Stringmessage) {Logger.Info(message); } }
Config configuration
Log4j
Copy Code
<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
Copy Code
<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>
Java-logback Get Method Name