java - 在 DropWizard 或 Jetty 应用程序中导致 404 的日志 URL
问题描述
我们正在运行 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
错误的方法吗?
解决方案
原来有两种方法
一个确实使用异常映射器:
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
- 如果我有更多时间,我会建议更改代码以添加它。
推荐阅读
- azure - 如何在 Azure Functions 中使用仅限 Azure Blob 的存储帐户 - 尝试创建 Blob 快照
- websocket - Websocket 使用统计
- java - 将元素添加到 ArrayList 时的 ConcurrentModification
- c - 为什么不能再次使用getopt?
- ruby-on-rails - 从另一个表中获取计数
- windows - 远程桌面服务:通过 PowerShell 进行 CAP 或 RAP
- java - Kotlin 在构造函数中调用非最终函数有效
- javascript - 实现侧边栏菜单的拖放
- r - 如何调整字符串替换功能以用 NA 替换数据框中的特定数字?
- python - 如何扫描不在维度 0 的张量?