Skip to content
Advertisement

Spring Boot – @Slf4j Logging Behavior differs in Test and in real Application

I have a sample class like this,

JavaScript

I have written a test case like this,

JavaScript

When I run this test the below items gets printed to console.

JavaScript

But when I run the printLogLevel() from application like this,

JavaScript

The below lines gets printed to console.

JavaScript

Below are the dependencies I have used for this testing.

JavaScript

and this is the parent pom version.

JavaScript

Now the question is, why there is a difference when I call the printLogLevel() method from test and from application. The debug level gets printed only from test. May I know why?

EDIT: Adding @SpringBootTest fixes this issue as suggest by @narendra, but it works only with junit5. I want the fix in junit4

Advertisement

Answer

@Slf4j annotation has nothing to do with Spring. Its a lombok annotation that gets into action during the compile time (while spring boot is a runtime framework). So putting this annotation is essentially the same as placing a static field that holds the reference to the initialized slf4j logger.

Now slf4j by itself doesn’t print anything, instead it relies on the underlying logging libraries which are actually able to print actual log messages.

So the changes are that you have something like logback-spring.xml or logback.xml in the sources of the application and the logging framework that SLF4J delegates to gets initialized from. Spring boot also has some sane defaults when it comes to logging. Since spring boot can also integrate with, say, log4j2, its hard to tell what exactly is happening in your application, so you should check that.

Now, during the test, the situation is different. You’ve shown a unit test that has nothing do to with spring. So it runs “on-its-own” with slf4j enabled.

And the actual behavior of logger again depends on how did you configure slf4j for tests.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement