Java 在DropWizard或Jetty应用程序中导致404的日志URL
我们正在运行DropWizard并尝试登录导致抛出404响应的URL 我们有一个catchall异常映射器,它接收一个Java 在DropWizard或Jetty应用程序中导致404的日志URL,java,jax-rs,jetty,dropwizard,Java,Jax Rs,Jetty,Dropwizard,我们正在运行DropWizard并尝试登录导致抛出404响应的URL 我们有一个catchall异常映射器,它接收一个NotFoundException。令人沮丧的是,该异常不包含导致抛出它的URL的上下文 此处的示例应用程序: 我们正在使用一个例外标记 public class NotFoundLogger implements ExceptionMapper<NotFoundException> { ExampleLogger logger = new ExampleL
NotFoundException
。令人沮丧的是,该异常不包含导致抛出它的URL的上下文
此处的示例应用程序:
我们正在使用一个例外标记
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());
}
}
}
一个例外标记是一种错误的方法吗?事实证明有两种方法
有人使用异常映射器:
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();
}
}
这不需要任何魔法,所以适合我,但你可以选择你的毒药
实际上,路径应该在NotFoundException
上-如果我有更多的时间,我会建议对代码进行更改以添加它。结果有两种方法
有人使用异常映射器:
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();
}
}
这不需要任何魔法,所以适合我,但你可以选择你的毒药
实际上,路径应该在NotFoundException
上-如果我有更多时间,我会建议对代码进行更改以添加它。您能否访问HttpServletRequest
,该请求在toResponse()
期间导致异常?或者使用UriInfo
per-Ooh,上下文机制看起来很有希望!但我讨厌那些无法发现的魔法!(为什么它不只是一个方法重载:D)您可以访问在toResponse()期间导致异常的HttpServletRequest
?或者使用UriInfo
per-Ooh,上下文机制看起来很有希望!但我讨厌那些无法发现的魔法!(为什么它不只是一个方法重载:D)
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());
}
}