com.healthy.common.log.access.handler.AbstractAccessLogHandler Maven / Gradle / Ivy
package com.healthy.common.log.access.handler;
import cn.hutool.core.builder.GenericBuilder;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import com.healthy.common.core.util.DesensitizedUtils;
import com.healthy.common.core.util.WebUtils;
import com.healthy.common.log.access.support.AccessLog;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.http.HttpHeaders;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import static com.healthy.common.log.constant.LogConstant.TRACE_ID;
/**
* AbstractAccessLogHandler
*
* @author xm.z
*/
@Slf4j
public abstract class AbstractAccessLogHandler implements AccessLogHandler {
/**
* 需要脱敏记录的参数
*/
private final List needDesensitizeParams = ListUtil.toList("password", "pass", "passConfirm");
/**
* 添加需要脱敏的参数
* @param params 需脱敏的参数
*/
public void addNeedDesensitizeParams(String params) {
needDesensitizeParams.add(params);
}
/**
* 获取参数信息
* @param request 请求信息
* @return 请求参数
*/
public String getParams(HttpServletRequest request) {
String params;
try {
Map paramMap = ServletUtil.getParamMap(request);
for (String paramKey : needDesensitizeParams) {
String value = paramMap.get(paramKey);
if (StrUtil.isNotBlank(value)) {
paramMap.put(paramKey, DesensitizedUtils.password(value));
}
}
params = JSONUtil.toJsonStr(paramMap);
}
catch (Exception e) {
params = "记录参数异常";
log.error("[prodLog],参数获取序列化异常", e);
}
return params;
}
/**
* 根据请求响应信息构建基础的访问日志
* @param request 请求信息
* @param response 响应信息
* @param instant 实例化器
* @param 参数类型
* @return {@link AccessLog}
*/
public T buildAccessLog(HttpServletRequest request, HttpServletResponse response,
Supplier instant) {
return GenericBuilder.of(instant).with(AccessLog::setUri, URLUtil.getPath(request.getRequestURI()))
.with(AccessLog::setTraceId, MDC.get(TRACE_ID)).with(AccessLog::setIp, WebUtils.getClientIP(request))
.with(AccessLog::setMethod, request.getMethod())
.with(AccessLog::setUserAgent, request.getHeader(HttpHeaders.USER_AGENT))
.with(AccessLog::setHttpStatus, response.getStatus())
.with(AccessLog::setCreateTime, LocalDateTime.now()).build();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy