激发 Web 框架日志记录请求和响应

2022-09-04 03:29:56

我正在使用Spark Web框架来开发REST API。有没有办法自动记录所有传入请求和传出响应(查询参数,标头,状态代码等),或者我是否需要为每个处理程序手动添加日志记录?

Spark文档没有关于这个主题的内容。

谢谢。


答案 1

这是我的解决方法。

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));
    });
}

答案 2

基于乔的回答...这是一个同时执行请求和响应的版本:

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();
}

推荐