Logo

dev-resources.site

for different kinds of informations.

Capturing and Testing Logs in Java with SLF4J and Logback: A Simple Guide

Published at
1/8/2025
Categories
java
testing
spring
slf4j
Author
la_andre_2fbbf84e88ae2f2
Categories
4 categories in total
java
open
testing
open
spring
open
slf4j
open
Author
24 person written this
la_andre_2fbbf84e88ae2f2
open
Capturing and Testing Logs in Java with SLF4J and Logback: A Simple Guide

When working on Java projects, logging is a vital tool for debugging and understanding application behavior. In some cases, you might want to write tests that verify specific log messages are produced under certain conditions. Here’s a simple guide to achieving that using SLF4J with Logback and a custom TestLogAppender.

Setting Up the Example

We’ll create a basic service that logs an error when an exception occurs, and a corresponding test to verify the log message.

Step 1: Add Logback Test Dependency

...
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-core</artifactId>
    <scope>test</scope>
</dependency>
...
Enter fullscreen mode Exit fullscreen mode

Step 2: Implementing the Service

Here’s a simple service that catches exceptions and logs an error:

package com.example.loggingdemo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SimpleService {
    private static final Logger logger = LoggerFactory.getLogger(SimpleService.class);

    public void performTask() {
        try {
            // Simulate some task that fails
            throw new IllegalArgumentException("Simulated exception");
        } catch (IllegalArgumentException e) {
            logger.error("An error occurred: {}", e.getMessage());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Creating a Custom TestLogAppender

This appender captures log messages during tests, enabling assertions on their content.

package com.example.loggingdemo;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;

public class TestLogAppender extends AppenderBase<ILoggingEvent> {
    private final StringBuilder logs = new StringBuilder();

    @Override
    protected void append(ILoggingEvent eventObject) {
        logs.append(eventObject.getFormattedMessage()).append("
");
    }

    public String getLogs() {
        return logs.toString();
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Writing the Test

Now, let’s write a test to verify the log output.

package com.example.loggingdemo;

import static org.assertj.core.api.Assertions.assertThat;

import ch.qos.logback.classic.Logger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;

public class SimpleServiceTest {
    private TestLogAppender logAppender;
    private SimpleService simpleService;

    @BeforeEach
    public void setup() {
        // Attach TestLogAppender to the logger
        logAppender = new TestLogAppender();
        logAppender.start();
        Logger logger = (Logger) LoggerFactory.getLogger(SimpleService.class);
        logger.addAppender(logAppender);

        // Initialize the service
        simpleService = new SimpleService();
    }

    @Test
    public void testPerformTaskLogsError() {
        // Act
        simpleService.performTask();

        // Assert
        String logs = logAppender.getLogs();
        assertThat(logs).contains("An error occurred: Simulated exception");
    }
}
Enter fullscreen mode Exit fullscreen mode

Important
Don't forget to start your log appender !

Step 5: Running the Test

When you run this test, it will confirm that the SimpleService logs the expected error message when an exception occurs.

How It Works

  • Custom Appender: The TestLogAppender captures log messages by overriding the append method of Logback’s AppenderBase.
  • Logger Configuration: During tests, we dynamically attach the custom appender to the target logger.
  • Assertions on Logs: Use the captured logs for assertions in your tests, verifying specific messages or patterns.

Conclusion

With this approach, you can confidently test your logging behavior, ensuring your application logs important events and errors as expected. This setup is versatile and can be adapted to more complex scenarios, such as testing log levels or message formatting.

Feel free to try this out and adapt it to your own projects!

Happy coding!

testing Article's
30 articles in total
Favicon
Top 10 Online Postman-Like Tools for API Testing and Development
Favicon
What Is POS Testing? A Step-by-Step Breakdown for Retail Success
Favicon
Maximize the efficiency of your tests with TAST
Favicon
Building a String Calculator with Test-Driven Development (TDD): A Step-by-Step Guide
Favicon
Building a new Chat
Favicon
Testing with JWT in .NET APIs
Favicon
Why Duplicating Environments for Microservices Backfires
Favicon
From Legacy to Modern: Creating Self-Testable APIs for Seamless Integration
Favicon
Research Paper Series: Using Lightweight Formal Methods to Validate a Key-Value Storage Node in Amazon S3
Favicon
End-to-End API Testing: How Mocking and Debugging Work Together
Favicon
Testing Temporary URLs in Laravel Storage
Favicon
The Role of AI in Cybersecurity: Opportunities and Challenges
Favicon
AI Software Testing: Revolutionizing Quality Assurance
Favicon
Testing with different text
Favicon
Need someone to contribute in writing test code for my open source project
Favicon
Finding the coverables
Favicon
5 Reasons Businesses Should Give Priority to Performance Testing
Favicon
5 Things to Know About Workday AI Testing
Favicon
Before TDD: Why you need to know what Mocks, Stubs, and Spies are?
Favicon
Software Testing Tasks with Challenges, Tools, and Best Practices
Favicon
Comprehensive Guide to Waits in Selenium 4
Favicon
Test Case Vs Test Scenario
Favicon
Introducing Codin: A CLI for Automated ML Model Testing in CI/CD
Favicon
Your Roadmap to Mastering k6 for Performance Testing
Favicon
Setting values in R6 classes, and testing with shiny::MockShinySession
Favicon
Introducing BlockBuster: is my asyncio event loop blocked?
Favicon
Wednesday Links - Edition 2025-01-08
Favicon
How to Connect External Speakers to Your Xbox Console
Favicon
Testing Pi Logic integrations.
Favicon
Capturing and Testing Logs in Java with SLF4J and Logback: A Simple Guide

Featured ones: