37

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.

shaedrich
  • 5,457
  • 3
  • 26
  • 42
MuchHelping
  • 581
  • 1
  • 4
  • 12

4 Answers4

34

Put this line of code on your @BeforeClass method and every given call will create a log just like using log.all() after every given:

RestAssured.filters(new RequestLoggingFilter(), new ResponseLoggingFilter());


Rest-Assured project:
https://github.com/rest-assured/rest-assured/blob/master/rest-assured/src/main/java/io/restassured/filter/log/RequestLoggingFilter.java

Luiz Gustavo
  • 441
  • 4
  • 5
30

I think you need to see the logs then test fails, in this case just use this configuration from rest assured:

RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();

Ștefan Teslari
  • 411
  • 4
  • 6
  • In what context? I tried putting that line in `@BeforeClass` but got `java.lang.NoClassDefFoundError: org/apache/groovy/io/StringBuilderWriter` – MarkHu May 11 '21 at 17:21
  • For `JUnit Jupyter` I added it on `@BeforeEach` – andras May 31 '21 at 19:11
25

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

RocketRaccoon
  • 2,559
  • 1
  • 21
  • 30
  • 3
    Thanks, I just added ResponseLoggingFilter to requestSpecification. ```addFilter(new ResponseLoggingFilter())``` – MuchHelping Jun 08 '17 at 14:12
1

You can define filters at the class level

public ClassName() {
    filters(new RequestLoggingFilter(), new ResponseLoggingFilter(), new ErrorLoggingFilter());
}
J.Klimov
  • 93
  • 10