Answer
Logging in Rest Assured
Logging is essential for debugging failing API tests. Rest Assured provides built-in logging through the .log() method.
Log Request Details
Java
// Log all request details (method, URL, headers, body)
given()
.log().all()
.contentType(ContentType.JSON)
.body("{ \"name\": \"John\" }")
.when()
.post("/api/users");
Output:
CODE
Request method: POST
Request URI: https://api.example.com/api/users
Headers: Content-Type=application/json
Body: { "name": "John" }
Log Response Details
Java
// Log all response details (status, headers, body)
given()
.when()
.get("/api/users/2")
.then()
.log().all()
.statusCode(200);
Specific Logging Options
Java
// Log only request headers
given().log().headers()
// Log only request body
given().log().body()
// Log only request parameters
given().log().params()
// Log only if request matches a condition
given().log().ifValidationFails()
// Log only response status
.then().log().status()
// Log only response headers
.then().log().headers()
// Log only response body
.then().log().body()
// Log only if test fails
.then().log().ifError()
.then().log().ifValidationFails()
Global Logging (Best Practice for CI/CD)
Java
@BeforeClass
public void setup() {
RestAssured.baseURI = "https://api.example.com";
// Only logs when a test fails — keeps CI output clean
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
}
Log to a File (for Reports)
Java
PrintStream fileOutput = new PrintStream(new File("target/api-logs.txt"));
RequestSpecification request = given()
.filter(new RequestLoggingFilter(fileOutput))
.filter(new ResponseLoggingFilter(fileOutput));
Recommended Logging Strategy
| Environment | Strategy |
|---|---|
| Local dev | .log().all() on failing tests |
| CI/CD | enableLoggingOfRequestAndResponseIfValidationFails() |
| Debugging | .log().all() on both request and response |
| Reports | Log to file using RequestLoggingFilter |
