Set restAssured to log all requests and responses globally

MuchHelping picture MuchHelping · May 30, 2017 · Viewed 33.8k times · Source

I want to enable logging for all restAssured responses and requests by default.

Here's what I do:

RestAssured.requestSpecification = new RequestSpecBuilder().
        setBaseUri("api").
        setContentType(ContentType.JSON).
        build().
        log().all();
RestAssured.responseSpecification = new ResponseSpecBuilder().
        build().
        log().all();

requestSpecification works alright, but with responseSpecification I get:

Cannot configure logging since request specification is not defined. You may be misusing the API.

I really don't want to use log().all() after each then.

Answer

RocketRaccoon picture RocketRaccoon · Jun 1, 2017

Add logging filters to RestAssured defaults, see filters and defaults.

To create a filter you need to implement the io.restassured.filter.Filter interface. To use a filter you can do:
given().filter(new MyFilter()). ..

There are a couple of filters provided by REST Assured that are ready to use:
1. io.restassured.filter.log.RequestLoggingFilter: A filter that'll print the request specification details.
2. io.restassured.filter.log.ResponseLoggingFilter: A filter that'll print the response details if the response matches a given status code.
3. io.restassured.filter.log.ErrorLoggingFilter: A filter that'll print the response body if an error occurred (status code is between 400 and 500)

Any filter could be added to request, spec or global defaults:

RestAssured.filters(..); // List of default filters