We are currently migrating from log4j to Logback, but we are having problems obtaining the "original" method name that triggered the log.
I'm calling it "original" because we have a centralized logger class (to hide and manipulate certain logs) and what's showing up in the logs is the method name from that centralized class.
In log4j we were able to obtain the "original" method name correctly.
Is Logback able to obtain it or not?
Loggers parameters:
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>
Results: (Method Name - Class Name)
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
EDIT - Full example
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's
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>
You need to make sure the 'caller data' is correct on the log event.
Probably one of these options will work:
Call ILoggingEvent::getCallerData() in your logger wrapper, to make sure the caller data is gathered early.
Maybe you can decorate the event in your centralised logger to spoof the caller data ILoggingEvent::getCallerData() call?
Or derive the caller data, then cast the ILoggingEvent to LoggingEvent, and call setCallerData() with you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With