使用JAX-RS将请求和响应记录在一处

埃德加·卡尔卡(Edgar Karka)

我有很多方法的RESTEasy Web服务器。我想要实现logback来跟踪所有请求和响应,但是我不想添加log.info()到每个方法中。

也许有一种方法可以将请求和响应收集到一个地方并记录下来。也许像RESTEasy上的HTTP请求过程链上的过滤器一样。

@Path("/rest")
@Produces("application/json")
public class CounterRestService {

    //Don't want use log in controler every method to track requests and responces
    static final Logger log = LoggerFactory.getLogger(CounterRestService.class); 

    @POST
    @Path("/create")
    public CounterResponce create(@QueryParam("name") String name) {
        log.info("create "+name)
        try {
            CounterService.getInstance().put(name);
            log.info("responce data"); // <- :((
            return new CounterResponce();
        } catch (Exception e){
            log.info("responce error data"); // <- :((
            return new CounterResponce("error", e.getMessage());
        }    
    }

    @POST
    @Path("/insert")
    public CounterResponce create(Counter counter) {
        try {
            CounterService.getInstance().put(counter);
            return new CounterResponce();
        } catch (Exception e){
            return new CounterResponce("error", e.getMessage());
        }
    }

    ...
}
卡西莫林

您可以创建过滤器并将其轻松绑定到需要记录的端点,从而使端点保持精简并专注于业务逻辑。

定义名称绑定注释

要将过滤器绑定到REST端点,JAX-RS提供了元注释@NameBinding,它可以按以下方式使用:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Logged { }

记录HTTP请求

@Logged注释将被用来装饰一个过滤器类,它实现ContainerRequestFilter,让您在处理请求:

@Logged
@Provider
public class RequestLoggingFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        // Use the ContainerRequestContext to extract information from the HTTP request
        // Information such as the URI, headers and HTTP entity are available
    }
}

@Provider注释标记的扩展接口,应该由JAX-RS是可发现的实现过程中提供扫描相运行时。

ContainerRequestContext帮助你提取HTTP请求信息。

以下是ContainerRequestContextAPI中从HTTP请求获取信息的方法,这些信息可能对您的日志有用:

记录HTTP响应

要记录响应,请考虑实施ContainerResponseFilter

@Logged
@Provider
public class ResponseLoggingFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, 
                       ContainerResponseContext responseContext) throws IOException {
        // Use the ContainerRequestContext to extract information from the HTTP request
        // Use the ContainerResponseContext to extract information from the HTTP response
    }
}

ContainerResponseContext帮助你提取HTTP响应信息。

以下是ContainerResponseContextAPI的一些方法,这些方法可从HTTP响应中获取对您的日志有用的信息:

将过滤器绑定到端点

要将过滤器绑定到端点方法或类,请使用@Logged上面定义的注释对它们进行注释。对于带有注释的方法和/或类,将执行过滤器:

@Path("/")
public class MyEndpoint {

    @GET
    @Path("{id}")
    @Produces("application/json")
    public Response myMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Logged
        // The logging filters won't be executed when invoking this method
        ...
    }

    @DELETE
    @Logged
    @Path("{id}")
    @Produces("application/json")
    public Response myLoggedMethod(@PathParam("id") Long id) {
        // This method is annotated with @Logged
        // The request logging filter will be executed before invoking this method
        // The response logging filter will be executed before invoking this method
        ...
    }
}

在上面的示例中,日志记录过滤器将仅针对进行执行,myLoggedMethod(Long)因为它带有注释@Logged

附加信息

除了ContainerRequestContextContainerResponseFilter接口中可用的方法外,您还可以ResourceInfo使用@Context以下方法注入过滤器

@Context
ResourceInfo resourceInfo;

它可以用来获取MethodClass匹配请求的URL其中:

Class<?> resourceClass = resourceInfo.getResourceClass();
Method resourceMethod = resourceInfo.getResourceMethod();

HttpServletRequest并且HttpServletResponse也可用于注射:

@Context
HttpServletRequest httpServletRequest;

@Context
HttpServletResponse httpServletResponse;

有关可以注入的类型,请参考此答案@Context

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

仅记录Soap请求和响应正文Jax WS

来自分类Dev

使用@XmlEnumValue映射JAX-RS枚举

来自分类Dev

无法使用内容类型-JAX-RS

来自分类Dev

在JAX-RS上使用UriBuilder的AbstractMethodError

来自分类Dev

在JAX-RS上使用subPath on方法

来自分类Dev

使用Jax WS获取响应头

来自分类Dev

在JAX-RS中使用Location标头创建响应

来自分类Dev

使用JAX-RS处理异步http请求?

来自分类Dev

使用WebLogic 12.2.1服务并发的JAX-RS请求

来自分类Dev

定制JAX-RS授权-在每个请求中使用JWT

来自分类Dev

使用jax-rs重定向获取请求并返回响应以解决CORS问题?

来自分类Dev

使用OAuth进行C#Web API请求/响应记录

来自分类Dev

@Inject CDI无法与JAX-RS一起使用

来自分类Dev

使用JAX-RS和JAXB将JSON响应映射到对象

来自分类Dev

将Web代理与Java 8 JAX-RS RESTEasy客户端一起使用

来自分类Dev

Jax-ws:在数据库中记录请求和响应

来自分类Dev

jax-rs,球衣原型,似乎无法使用@WebListener

来自分类Dev

如何使用JAX-RS实现返回的子资源

来自分类Dev

如何使用JAX-RS获取整个子路径?

来自分类Dev

使用JAX-RS在REST服务中的可重用性

来自分类Dev

如何使用JAX-RS Web服务打开JSF页面?

来自分类Dev

使用来自JAX-RS Web服务的安全EJB

来自分类Dev

读取JSON以使用JAX-RS进行映射

来自分类Dev

使用JAX-RS 2.0客户端API的POST

来自分类Dev

不使用Spring的带有CXF的JAX-RS

来自分类Dev

JAX-RS使用的无状态EJB中的@Context注入

来自分类Dev

在相同的方法上使用Jax-Rs @Get @Post

来自分类Dev

如何通过Pentaho(水壶)正确使用JAX-RS(RESTEasy)

来自分类Dev

使用来自JAX-RS Web服务的安全EJB