Reputation: 5011
I'm using the Spark web framework to develop a REST API. Is there a way to automatically log all incoming requests and outgoing responses (query params, headers, status codes, etc) or do I need to manually add logging for each one of the handlers?
The Spark documentation has nothing on this subject.
Thanks.
Upvotes: 14
Views: 3591
Reputation: 67
This should be enough:
public static void main(String[] args) {
// add logger
after((request, response) -> {
LOG.info(String.format("%s %s", request.requestMethod(), request.url()));
});
}
Upvotes: 0
Reputation: 9418
Building upon Joe's answer... here's a version that'll do both request and reponse:
public static void main(String[] args) {
... all your other handlers
// add logger
after((request, response) -> {
LOG.info(requestAndResponseInfoToString(request, response));
});
}
private static String requestAndResponseInfoToString(Request request, Response response) {
StringBuilder sb = new StringBuilder();
sb.append(request.requestMethod());
sb.append(" " + request.url());
sb.append(" " + request.body());
HttpServletResponse raw = response.raw();
sb.append(" Reponse: " + raw.getStatus());
sb.append(" " + raw.getHeader("content-type"));
try {
sb.append(" body size in bytes: " + response.body().getBytes(raw.getCharacterEncoding()).length);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return sb.toString();
}
Upvotes: 1
Reputation: 3620
Here's was my workaround.
private static String requestInfoToString(Request request) {
StringBuilder sb = new StringBuilder();
sb.append(request.requestMethod());
sb.append(" " + request.url());
sb.append(" " + request.body());
return sb.toString();
}
public static void main(String[] args) {
// Bunch of handlers
before((request, response) -> {
log.info(requestInfoToString(request));
});
}
Upvotes: 12