Skip to content

log4j-iostreams in 3.0.0-beta2 has bug that fails logCaptor  #3849

@nagkumar

Description

@nagkumar
package com.shivoham.sys2log.logs.log4j.tests;

import com.shivoham.sys2log.logs.log4j.SOutRedirectLog4J2;
import nl.altindag.log.LogCaptor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.io.IoBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertTrue;

public final class TestSOutRedirectLog4J2
{
    protected static final LogCaptor logCaptor = LogCaptor.forClass(SOutRedirectLog4J2.class);

    private static final Logger log4jLogger = LogManager.getLogger(SOutRedirectLog4J2.class);

    @BeforeEach
    public void setUp()
    {
	OutputStream lOutputStreamFromLogger = IoBuilder.forLogger(log4jLogger).buildOutputStream();
	System.setOut(new PrintStream(lOutputStreamFromLogger));
	logCaptor.clearLogs();
    }

    @Test
    public void redirect()
    {
	new SOutRedirectLog4J2().doPrint();
	assertTrue(hasPartialMatch(logCaptor.getLogs(), "This message will be logged via Log4j2."),
		   "Should print This message will be logged via Log4j2.");
    }

    private static final boolean hasPartialMatch(final List<String> aStringList, final String aSubString)
    {
	return aStringList.stream().anyMatch(s -> s.trim().contains(aSubString.trim()));
    }
}

package com.shivoham.sys2log.logs.log4j;

public class SOutRedirectLog4J2
{
    public void doPrint()
    {
	System.out.println("This message will be logged via Log4j2.");
    }
}

dependencies {
implementation("org.apache.logging.log4j:log4j-core:3.0.0-beta3")
    implementation("org.apache.logging.log4j:log4j-api:2.25.1")
    implementation("org.apache.logging.log4j:log4j-iostreams:2.25.1")
}

This code fails to show redirected content in logCaptor.getLogs().. however with the same version of logCaptor and 2.25.1 of log4j-iostreams it works

Complete source code is at
https://github.com/nagkumar/java/tree/main/tutorials/testing/junit5/logs/sys2log/sys2log

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIncorrect, unexpected, or unintended behavior of existing code

    Type

    No type

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions