记录器调用泽西项目

时间:2016-07-05 09:02:18

标签: java jersey tomcat8

我使用Jersey-1.19,Jackson-1.9.2,log4j-1.2,Java和Servlet技术创建了一个WS REST项目。为了运行该项目,我使用tomcat-8。

我需要配置文件log4j.properties,以便向我展示WS REST中所有可用方法的所有REQUEST。有可能吗?

基本上,我需要做什么记录器所有REQUEST?

我的log4j.properties是:

#### Use two appenders, one to log to console, another to log to a file
logFolder = D:/logs
log4j.rootCategory=debug

#### First appender writes to console
log4j.appender.myConsole=org.apache.log4j.ConsoleAppender
log4j.appender.myConsole.Threshold=debug
log4j.appender.myConsole.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.myConsole.layout.ConversionPattern=%d{DATE} %-5p: [%C{1}.%M(%L)] %m%n

2 个答案:

答案 0 :(得分:1)

如果要自定义请求和响应的日志消息,可以创建自定义日志记录过滤器。

public class CustomLoggingFilter extends LoggingFilter implements ContainerRequestFilter, ContainerResponseFilter {

    private static Logger logger = Logger.getLogger(CustomLoggingFilter.class.getName());

    @Override
    public ContainerRequest filter(ContainerRequest request) {
        StringBuilder sb = new StringBuilder();
        sb.append("\nMethod : ").append(request.getMethod().toUpperCase())
                                .append("  Path : ").append(request.getRequestUri().getPath())
                                .append("\nHeaders : ").append(request.getRequestHeaders());

        logger.log(Level.INFO, "\nHTTP REQUEST" + sb.toString());

        return request;
    }

    @Override
    public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
        ObjectMapper objectMapper = new ObjectMapper();
        StringBuilder sb = new StringBuilder();
        sb.append("\nHeaders : ").append(response.getHttpHeaders());
        sb.append("\nStatus : ").append(response.getStatus());

        try {
            sb.append("\nEntity : ").append(objectMapper.writeValueAsString(response.getEntity()));
        } catch (Exception e) {
            logger.log(Level.INFO, "\nEntity : ERROR in converting entity to JSON for logging. " + e.getMessage());
        }

        logger.log(Level.INFO, "\nHTTP RESPONSE" + sb.toString());

        return response;
    }
}

在web.xml中,你应该使用" [packagename] .CustomLoggingFilter"而不是" com.sun.jersey.api.container.filter.LoggingFilter"

答案 1 :(得分:0)

我的回答是http://wpcertification.blogspot.pt/2012/06/enabling-request-and-response-logging.html

基本上,我需要在web.xml中添加Jersey REST Servlet定义中的以下参数:

<init-param>
    <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
    <param-value>com.sun.jersey.api.container.filter.LoggingFilter</param-value>
</init-param>
<init-param>
    <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
    <param-value>com.sun.jersey.api.container.filter.LoggingFilter</param-value>
</init-param>