# Jersey 使用过滤器记录请求和响应实体

> 原文： [https://howtodoinjava.com/jersey/jersey-custom-logging-request-and-response-entities-using-filter/](https://howtodoinjava.com/jersey/jersey-custom-logging-request-and-response-entities-using-filter/)

默认情况下，Jersey 使用 JUL 进行日志记录 - 不会在日志中打印请求/响应实体主体。 要打印实体内容，必须创建自己的`LoggingFiler`，并将其注册为默认值`org.glassfish.jersey.filter.LoggingFilter`。 在此示例中，我正在创建一个这样的基本`CustomLoggingFilter`，它扩展了`org.glassfish.jersey.filter.LoggingFilter`并实现了`ContainerRequestFilter`和`ContainerResponseFilter`接口，以便它可以拦截正在进行的请求和响应。

```java
Table of Contents

Create CustomLoggingFilter
Register CustomLoggingFilter
Log statements with default LoggingFilter 
Log statements with CustomLoggingFilter
```

## 创建`CustomLoggingFilter`

让我们直接转到此 Jersey 演示的自定义日志记录过滤器类。

```java
package com.howtodoinjava.jersey.provider;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;

import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.message.internal.ReaderWriter;

public class CustomLoggingFilter extends LoggingFilter implements ContainerRequestFilter, ContainerResponseFilter 
{
	@Override
	public void filter(ContainerRequestContext requestContext)	throws IOException 
	{
		StringBuilder sb = new StringBuilder();
		sb.append("User: ").append(requestContext.getSecurityContext().getUserPrincipal() == null ? "unknown"
						: requestContext.getSecurityContext().getUserPrincipal());
		sb.append(" - Path: ").append(requestContext.getUriInfo().getPath());
		sb.append(" - Header: ").append(requestContext.getHeaders());
		sb.append(" - Entity: ").append(getEntityBody(requestContext));
		System.out.println("HTTP REQUEST : " + sb.toString());
	}

	private String getEntityBody(ContainerRequestContext requestContext) 
	{
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		InputStream in = requestContext.getEntityStream();

		final StringBuilder b = new StringBuilder();
		try 
		{
			ReaderWriter.writeTo(in, out);

			byte[] requestEntity = out.toByteArray();
			if (requestEntity.length == 0)
			{
				b.append("").append("\n");
			}
			else
			{
				b.append(new String(requestEntity)).append("\n");
			}
			requestContext.setEntityStream( new ByteArrayInputStream(requestEntity) );

		} catch (IOException ex) {
			//Handle logging error
		}
		return b.toString();
	}

	@Override
	public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException 
	{
		StringBuilder sb = new StringBuilder();
		sb.append("Header: ").append(responseContext.getHeaders());
		sb.append(" - Entity: ").append(responseContext.getEntity());
		System.out.println("HTTP RESPONSE : " + sb.toString());
	}
}

```

## 注册`CustomLoggingFilter`

要注册此`CustomLoggingFilter`，请以这种方式注册。

```java
package com.howtodoinjava.jersey;

import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;

import com.howtodoinjava.jersey.provider.CustomLoggingFilter;

public class CustomApplication extends ResourceConfig 
{
	public CustomApplication() 
	{
		packages("com.howtodoinjava.jersey");
		register(JacksonFeature.class);

		register(CustomLoggingFilter.class);
	}
}

```

## 使用默认`LoggingFilter`的日志语句

现在，如果您尝试使用不带`CustomLoggingFilter`的任何现有 REST API，日志将以这种方式显示。

**请求**

![Jersey-custom-logging](img/469f4bd4917358d1f9e9bda5b1752d8a.png)

**日志**

```java
Sep 30, 2015 6:18:41 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 1 * Server has received a request on thread http-bio-8080-exec-4
1 > POST http://localhost:8080/JerseyDemos/rest/employees
1 > accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
1 > accept-encoding: gzip, deflate
1 > accept-language: null
1 > cache-control: no-cache
1 > connection: keep-alive
1 > content-length: 35
1 > content-type: application/json; charset=UTF-8
1 > host: localhost:8080
1 > pragma: no-cache
1 > user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0

Sep 30, 2015 6:18:41 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 1 * Server responded with a response on thread http-bio-8080-exec-4
1 < 200
1 < Content-Type: application/json
```

## 使用`CustomLoggingFilter`的日志语句

添加`CustomLoggingFilter`后，您将获得更好的日志，如下所示。

```java
HTTP REQUEST : User: unknown - Path: employees - Header: {host=[localhost:8080], user-agent=[Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0], accept=, accept-language=[null], accept-encoding=[gzip, deflate], content-type=[application/json; charset=UTF-8], content-length=[35], connection=[keep-alive], pragma=[no-cache], cache-control=[no-cache]} - Entity: {"id":2,"name":"Alex Kolenchiskey"}

HTTP RESPONSE : Header: {Content-Type=[application/json]} - Entity: Employee [id=2, name=Alex Kolenchiskey]
```

请根据需要随时从日志语句中添加/删除信息。 您可以在这些日志中添加许多其他有用的信息。

**祝您学习愉快！**