第一步:配置logback.xml
<configuration>
<!-- INFO级别日志 appender -->
<appender name="apiInfoAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${XXX_HOME}/log/%d{yyyy-MM-dd}/xxx-api.log</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%level] %logger - %msg%n</pattern>
</encoder>
</appender>
<logger name="apiFilterLogger" level="INFO" additivity="false">
<appender-ref ref="apiInfoAppender" />
</logger>
</configuration>
第二步:代码里使用Logger
@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/rest/v1/*", filterName = "apiFilter")
public class ApiFilter implements Filter {
private static final String API_FILTER_LOGGER_NAME = "apiFilterLogger";
@Value("${api.filter.enable:false}")
private boolean apiFilerEnable;
private Logger logger = LoggerFactory.getLogger(API_FILTER_LOGGER_NAME);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (apiFilerEnable) {
HttpServletRequest httprequest = (HttpServletRequest) request;
String currentIp = request.getRemoteAddr();
Enumeration<String> e = httprequest.getHeaderNames();
logger.info("============================API Request Start==============================");
String msg = String.format(">>API Request:[%s] [%s]", httprequest.getMethod(), httprequest.getRequestURL());
logger.info(msg);
logger.info(">>>>>Remote Addr:" + httprequest.getRemoteAddr());
logger.info(">>>>>Query String:" + httprequest.getQueryString());
logger.info("============Header=================");
while (e.hasMoreElements()) {
String k = e.nextElement();
logger.info(">>>>>" + k + " = " + httprequest.getHeader(k));
}
Map<String, String[]> paramMap = httprequest.getParameterMap();
logger.info("============Parameter Map=================");
paramMap.entrySet().forEach(x -> {
logger.info(">>>>>" + x.getKey() + "=" + Joiner.on(",").join(x.getValue()));
});
logger.info("===================================================================");
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
网友评论