gpt4 book ai didi

java - 记录器调用 Jersey 项目

转载 作者:行者123 更新时间:2023-12-01 09:44:13 25 4
gpt4 key购买 nike

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

我需要配置文件 log4j.properties 来向我显示 WS REST 中可用的所有方法的所有请求。这可能吗?

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

我的 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

最佳答案

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

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”

关于java - 记录器调用 Jersey 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38199287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com