简体   繁体   中英

Log Jersey entity as JSON as response

I'm a Jersey newbie and I need to log the JSON response. I wish to take the entity and convert it to JSON exactly as done by the Jersey framework does (same mapper, etc.). Is there a way to extract its mapper (and call, for example, its writeValueAsString)?

You don't specify which package you use for producing the JSON response (neither you explain much about your jersey server), but I will assume you use Jackson .

You have some tracing in Jersey, take a look here , but as fas as I know it does not do what you need.

But first of all you should implement a LoggingFilter ,

public class YourLoggingFilter implements ContainerResponseFilter {

    @Override
    public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
            throws IOException {
        ...

    }

}

And I assume you extend the ResourceConfig class to add resources, you need to add the new filter here:

public class YourApplication extends ResourceConfig {

    public YourApplication() {
        super();

        register(YourAuthenticationRequestFilter.class, Priorities.AUTHENTICATION);
        register(YourExceptionMapper.class);
        register(YourLoggingFilter.class);

        packages("...");
    }
}

And finally, a simple way to log your response inside YourLoggingFilter would be (here I assume Jackson , but this is just an example, I don't know what logger you are using, but don't open a file every time you do a request!!!)

Object obj = responseContext.getEntity();
ObjectMapper om = new ObjectMapper();
File file = new File("...");
try {
    OutputStream out = new FileOutputStream(file);
    om.writeValue(out, obj);
} catch (IOException e) {
    // this could fail but you don't want your request to fail
    e.printStackTrace();
}

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM