Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture logs with logCaptor or MOCKITO?

I am following these solution:

https://github.com/Hakky54/log-captor

https://dzone.com/articles/unit-testing-log-messages-made-easy

i am using

            <groupId>io.github.hakky54</groupId>
            <artifactId>logcaptor</artifactId>
            <version>2.2.0</version>
            <scope>test</scope>

My code is exactly same like:

package com.filter.requeststatistics.writer;

import com.testutil.data.TestDataUtil;
import nl.altindag.log.LogCaptor;
import org.junit.Test;

import java.util.List;
public class StatisticsModuleImplTest {


    @Test
    public void testSuccessCall(){

        RequestStatisticsInput input = TestDataUtil.createFilledTestData(RequestStatisticsInput.class);
        input.getBrandId();

        LogCaptor logCaptor = LogCaptor.forClass(StatisticsModuleImpl.class);

        StatisticsModuleImpl statisticsModule = new StatisticsModuleImpl();
        statisticsModule.writeRequestStatistic(input);

        List<String> infoLogs = logCaptor.getInfoLogs();
        //List<String> logs = logCaptor.getLogs();
        //List<String> debugLogs = logCaptor.getDebugLogs();
        //List errorLogs = logCaptor.getErrorLogs();
        //logs.size();
        //assertThat(logCaptor.getLogs()).containsExactly("a");

    }

but infoLogs size is zero (and also other log types when set are also zero)

my StatisticsModuleImpl class is:

package com.filter.requeststatistics.writer;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


public class StatisticsModuleImpl implements StatisticsModule {

    private static final Logger LOGGER = LogManager.getLogger(StatisticsModuleImpl.class);
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void writeRequestStatistic(RequestStatisticsInput input) {

        try {
            String jsonString = mapper.writeValueAsString(input);
            LOGGER.info("received request: " + jsonString);
        } catch (JsonProcessingException ignored) {
            // Should never happen, nevertheless we should not stop serving requests if it does.
            LOGGER.error("Exception while trying to log request statistic: " + input.toString(), ignored);
        }

    }

}

I am not able to understand whats the problem ???? All the imports are same. When i debug my test, the field logCaptor.listAppender, there the i dont see any Appenders. My log4j.properties file is:

log4j.rootLogger=DEBUG, console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

and log4j2.xml is

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Properties>
        <Property name="log-path">target/logs</Property>
    </Properties>
    <Appenders>
        <Console name="stdout" target="SYSTEM_OUT">
            <PatternLayout pattern=" %-5p %d{ABSOLUTE} %5p %c{1}:%L - %m%n"/>
        </Console>
        <File name="testlogfile" fileName="${log-path}/test.log" append="false">
            <PatternLayout>
                <Pattern>%d{ABSOLUTE} %5p %c{1}:%L - %m%n</Pattern>
            </PatternLayout>
            <ThresholdFilter level="info"  onMatch="ACCEPT" onMismatch="DENY"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="DEBUG" additivity="false" includeLocation="true" >
            <AppenderRef ref="testlogfile"/> 
            <AppenderRef ref="stdout"/> 
        </Root>
    </Loggers>
</Configuration>
like image 785
MiGo Avatar asked Oct 31 '25 22:10

MiGo


1 Answers

It looks like LogCaptor is missing an adapter to have it working with apache logger. I will publish a fix this week, for the time being you can add the following dependency and that should do the trick:

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-to-slf4j</artifactId>
    <version>2.14.0</version>
    <scope>test</scope>
</dependency>

I will update this answer when the fix is published.

============= UPDATE #1 =============

You don't need the workaround which I shared above. The fix is present in the latest version. Could you bump it to 2.3.1 or use the latest version from here: Maven Central, retry it and share your results here?

like image 178
Hakan54 Avatar answered Nov 02 '25 22:11

Hakan54



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!