javalogginglog4j2rest-assured

How to control Rest Assured's logging filters through log4j2.xml?


I want to redirect RestAssured 5.3.0 logging to log4j2 and be able to control the logging from log4j2.xml config.

My App example:

package org.example;

import io.restassured.RestAssured;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.filter.log.ResponseLoggingFilter;
import org.apache.logging.log4j.io.IoBuilder;

public class App {

    static {
        var logStream = IoBuilder.forLogger(RestAssured.class).buildPrintStream();

        var requestFilter = new RequestLoggingFilter(logStream);
        var responseFilter = new ResponseLoggingFilter(logStream);

        RestAssured.filters(requestFilter, responseFilter);
    }

    public static void main(String[] args) {
        RestAssured.given().get("https://httpbin.org/");
    }
}

My log4j2.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" strict="true">

    <Appenders>
        <Appender type="Console" name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{3} - %msg%n"/>
        </Appender>
    </Appenders>

    <Loggers>
        <Root level="debug">
            <AppenderRef ref="Console"/>
        </Root>

        <Logger name="io.restassured" level="OFF"/>

    </Loggers>

</Configuration>

Output:

13:25:43.198 [main] OFF   io.restassured.RestAssured - Request method:  GET
13:25:43.200 [main] OFF   io.restassured.RestAssured - Request URI: https://httpbin.org/
13:25:43.200 [main] OFF   io.restassured.RestAssured - Proxy:           <none>
13:25:43.200 [main] OFF   io.restassured.RestAssured - Request params:  <none>
  1. Is this the correct approach for redirecting RestAssured logging to log4j2?
  2. Why logs still show but with level OFF? Actually the logs show with whatever level I set for the io.restassured logger.

Solution

  • Since you didn't specify a logging level in IoBuilder, the log events are issued with the configured logging event (OFF). You just need to call setLevel:

    IoBuilder.forLogger(RestAssured.class).setLevel(Level.DEBUG).buildPrintStream();
    

    Remark: IMHO using IoBuilder is never the best approach if you have other choices: you don't control where each log event ends. In your case, you could write a Filter that calls the Log4j API directly.