我使用Spark web framework开发REST API。有没有办法自动记录所有传入的请求和传出的响应(查询参数,标题,状态代码等),还是我需要为每个处理程序手动添加日志记录?
Spark文档中没有关于此主题的内容。
感谢。
答案 0 :(得分:10)
这是我的解决方法。
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));
});
}
答案 1 :(得分:0)
以乔的回答为基础......这里有一个既要求又回应的版本:
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();
}
答案 2 :(得分:0)
这应该足够了:
public static void main(String[] args) {
// add logger
after((request, response) -> {
LOG.info(String.format("%s %s", request.requestMethod(), request.url()));
});
}