How to get rest-assured log into something printable in a text file

user2003186 picture user2003186 · Jan 23, 2013 · Viewed 11.8k times · Source

I'm working into a method trying to change the default rest-assured log (which goes to the console) to a file using log4j.

It's a JUnit project which methods finally call to a REST facade, which have methods like this one.

 private ResponseSpecification responseSpecification(RequestSpecification requestSpecification, Matcher matcher, int statusCode) {
        ResponseSpecification responseSpecification = requestSpecification.expect().statusCode(StatusCode).body(".", is(matcher));
        if (log) {
            responseSpecification = responseSpecification.log().all();
        }
        return responseSpecification;
    }

Following the official doc, I've changed the method like this:

private ResponseSpecification responseSpecification(RequestSpecification requestSpecification, Matcher matcher, int statusCode) {
    final StringWriter writer = new StringWriter();
    final PrintStream captor = new PrintStream(new WriterOutputStream(writer), true);
    ResponseSpecification responseSpecification = requestSpecification.filter(logResponseTo(captor)).expect().statusCode(statusCode).body(".", is(matcher));
    System.out.println("writer = " + writer.toString() + " <-");
    return responseSpecification;
}

But writer.toString() prints always a void string (the old implementation works fine). Maybe I'm doing something wrong, but what? :(

I need to get something printable which can be managed by log4j, in this or other way.

Can anyone help me?

Answer

user2003186 picture user2003186 · Jan 25, 2013

I've just solved the problem writing this into the RestSuite.setUp() method

RestAssured.config = config().logConfig(new LogConfig(defaultPrintStream));

and keeping intact the old code.

private ResponseSpecification responseSpecification(RequestSpecification requestSpecification, Matcher matcher, int statusCode) {
    ResponseSpecification responseSpecification = requestSpecification.expect().statusCode(StatusCode).body(".", is(matcher));
    if (log) {
        responseSpecification = responseSpecification.log().all();
    }
    return responseSpecification;
}

I hope it can help to someone in a future.