【问题标题】:Log URL that caused 404 in a DropWizard or Jetty application在 DropWizard 或 Jetty 应用程序中导致 404 的日志 URL
【发布时间】:2019-05-08 09:55:14
【问题描述】:

我们正在运行 DropWizard 并尝试记录导致抛出 404 响应的 URL

我们有一个接收NotFoundException 的包罗万象的异常映射器。令人沮丧的是,该异常不包含导致它被抛出的 URL 的上下文。

此处的示例应用程序:https://github.com/pauldambra/not.found.example

我们使用的是ExceptionMapper

public class NotFoundLogger implements ExceptionMapper<NotFoundException> {

    ExampleLogger logger = new ExampleLogger();

    @Override
    public Response toResponse(final NotFoundException exception) {
        logger.error(urlFrom(exception), exception);
        return Response.status(404).build();
    }

    private String urlFrom(final NotFoundException exception) {
        return "why is this not a property on the exception?!";
    }

    private class ExampleLogger {
        void error(final String notFoundUrl, final NotFoundException exception) {
            System.out.println("someone tried to load " + notFoundUrl);
            System.out.println(exception.getMessage());
        }
    }
}

如果我们在有人请求应用程序不提供的 URL 时查看应用程序日志,我们会看到应用程序可以记录它正在为路径返回 404,但我们的自定义记录器无权访问该 URL

someone tried to load why is this not a property on the exception?!
HTTP 404 Not Found
127.0.0.1 - - [08/May/2019:09:53:47 +0000] "GET /ping/pong HTTP/1.1" 404 

ExceptionMapper 是错误的方法吗?

【问题讨论】:

标签: java jax-rs jetty dropwizard


【解决方案1】:

原来有两种方法

确实使用了异常映射器:

public class NotFoundLogger implements ExceptionMapper<NotFoundException> {

    // magically inject a thing
    // remember that magic is for evil wizards
    @Context
    private HttpServletRequest request;

    private ExampleLogger logger = new ExampleLogger();

    @Override
    public Response toResponse(final NotFoundException exception) {
        final StringBuffer absolutePath = HttpUtils.getRequestURL(request);
        logger.error("exception mapper: " + absolutePath, exception);
        return Response.status(404).build();
    }
}

这可行,但不是很容易被发现。

您还可以添加响应过滤器

public class NotFoundLoggingFilter implements ContainerResponseFilter {
    private ExampleLogger logger = new ExampleLogger();

    @Override
    public void filter(ContainerRequestContext requestContext,
                       ContainerResponseContext responseContext) {
        if (responseContext.getStatus() != 404) {
            return;
        }

        final URI absolutePath = requestContext.getUriInfo().getAbsolutePath();
        logger.error("filter: " + absolutePath, new NotFoundException());
    }
}

这不需要任何魔法,所以很适合我,但你可以选择你的毒药。

真的,路径应该在 NotFoundException 上 - 如果我有更多时间,我会建议更改代码以添加它。

【讨论】:

    猜你喜欢
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 2018-06-01
    • 2018-01-26
    • 1970-01-01
    • 2016-04-08
    • 2014-06-17
    相关资源
    最近更新 更多