I'm using SLF4j with Log4j2. The SLF4j version is 1.7.22 and the Log4j2 version is 2.8.2. When I log an exception with Log4j2 in a method, it only logs one line. I expected the log to show the full stack trace of the exception in my log. Due to this question, I am unable to identify the cause of the NullPointerException.
Here is my code snippet:
try{
// Some code
}catch (Throwable e){
logger.error("Occur exception -> ", e);
}
The log file only has one line.
java.lang.NullPointerException: null
My log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration packages="com.changing" >
<Appenders>
<!-- DailyFile & Log file Name format by pattern -->
<RollingFile name="DailyFile"
fileName="C:/logs/log.log"
filePattern="C:/logs/log-%d{yyyyMMdd}.log">
<PatternLayout charset="UTF-8"
pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] [%t] %c{2}:%L - %msg%n" />
<Policies>
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.contoso" level="debug">
<AppenderRef ref="DailyFile" />
</Logger>
</Loggers>
</Configuration>
I have checked that this code correctly writes the full stack trace in my environment and test environment. However, when the same code runs on the production environment, it only shows one line.
If I manually throw the exception, it will log the full stack trace even in the production environment. However, when the NullPointerException occurs, it will only log one line.
I have checked that the log4j2.xml file is the same between the test environment and the production environment, only the file path is different.
I also tested throwing an exception in a different method in the same class, and it showed the full stack trace even in the production environment. Method A only showed one line of the full stack trace, whereas Method B showed the full stack trace.
class A {
private static Logger logger = LogManager.getLogger(A.class);
void methodA(){
try{
// Some code
}catch (Throwable e){
logger.error("Occur exception -> ", e);
}
}
void methodB(){
try{
// Some code
}catch (Throwable e){
logger.error("Occur exception -> ", e);
}
}
}