Search code examples
javalogginglogback

logback create a new log instance programmatically


I am having a small query with LogBack in Java and i'm hoping someone on the forum might have the solution for me.

I am running some tests, I can run those tests in singles or multiples. When I am running them in multiples is where I get the issue. I want to log file to change depending on the name of the test case. For example when I run 10 tests and test 1 id 1, when that finishes and test 2 starts I want that to be reflected to the log file and I want a second log file to be created with id 2.

I hope that makes sense, and if you have any additional questions please don't hesitate to ask.

Thank you in advance.


Solution

  • You can use Logback's SiftingAppender.

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
    
        <appender name="SIFTER" class="ch.qos.logback.classic.sift.SiftingAppender">
            <discriminator>
                <key>testName</key>
                <defaultValue>UNKNOWN</defaultValue>
            </discriminator>
            <sift>
                <appender name="FILE-${testName}" class="ch.qos.logback.core.FileAppender">
                    <file>test-${testName}.log</file>
                    <layout class="ch.qos.logback.classic.PatternLayout">
                        <pattern>...</pattern>
                    </layout>
                </appender>
            </sift>
        </appender>
    
        <root level="ALL">
            <appender-ref ref="SIFTER" />
        </root>
    </configuration>
    

    The value of testName will be substituted into the log file name. You set testName via org.slf4j.MDC. For example;

    String testName = "...";
    MDC.put("testName", testName);
    
    // run your test
    // ...
    
    // remove the test name from MDC ready for the next test to set its own name
    MDC.remove("testName");
    

    You could use JUnit4's TestName Rule to get the current test name and then put/remove in @Before, @After methods.