Log Jersey entity as JSON as response

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 23:20:15

问题


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)?


回答1:


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.



来源:https://stackoverflow.com/questions/34850858/log-jersey-entity-as-json-as-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!