Search code examples
javaspring-bootperformancelogginglog4j2

log4j2 in Spring Boot slows down my application significantly


I built a REST API with Spring Boot and I switched my logging framework to log4j2 by adding an exclusion of the default logger in my pom.xml:

<exclusion>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-logging</artifactId>
</exclusion>

As well as including log4j2 instead:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

I'm experiencing insane slowdowns of my REST API. I realized that log4j2 is calling the toString() methods of my data JPA entities seemingly "out of nowhere" (e.g. I didn't specifically write log statements to log them out). I suppose this causes massive overhead (by potentially also fetching more entities from the database).

By reverting back to the default logger Logback the performance is "normal" again. Logback also does not call the toString() methods "out of nowhere". Why is log4j2 so inefficient here and can this behavior of calling my toString() methods "out of nowhere" be turned off?


Solution

  • Even though I wasn't able to figure out why log4j2 is mysteriously calling my entity's toString() methods, severely degrading performance, I decided to use the default Logback logger and I ended up being quite happy with it, so I don't really need to use log4j2 anymore. After all, Logback is also the default logger for Spring Boot. Sometimes it's better not to break a running setup.