我们正在运行DropWizard并尝试删除导致引发404响应的URL记录
我们有一个接受NotFoundException
的综合异常映射器。令人沮丧的是,该异常不包含导致该URL引发的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
是这样做的错误方法吗?
答案 0 :(得分:4)
结果有两种方法
一个人确实使用了异常映射器:
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
上-如果我有更多时间,我建议更改代码以添加它。