场景:
项目中通常要将系统的操作记录作为日志保存下来,以便于记录用户的操作行为和在出现系统故障时分析系统问题,为便于在微服务间保持代码的低侵入性和日志数据的规范性,可使用自定义日志注解来达到上述目的,配合Redis的发布订阅模式达到应用间的解耦(也可以使用消息中间件MQ、Spring Event事件、Spring异步处理等机制)。
- 日志自定义注解
可定义如title、moduleName(模块名称)、operationType(操作类型)等。
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
String title() default "";
ModuleEnum moduleName() default ModuleEnum.OTHER;
OperationTypeEnum operationType() default OperationTypeEnum.OTHER;
boolean isSaveRequestData() default true;
boolean isSaveResponseData() default true;
}
- 模块名称枚举
public enum ModuleEnum {
RBAC("RBAC", "RBAC基础服务"),
OTHER("OTHER","其他");
private final String type;
private final String desc;
ModuleEnum(String type, String desc) {
this.type = type;
this.desc = desc;
}
public String getType() {
return type;
}
public String getDesc() {
return desc;
}
}
- 业务操作类型枚举
public enum OperationTypeEnum {
OTHER("OTHER","其他操作"),
INSERT("INSERT","新增"),
UPDATE("UPDATE","更新"),
DELETE("DELETE","删除"),
GRANT("GRANT","授权"),
EXPORT("EXPORT","导出"),
IMPORT("IMPORT","导入"),
LOGIN("LOGIN","登录"),
LOGOUT("LOGOUT","退出");
private final String type;
private final String desc;
OperationTypeEnum(String type, String desc) {
this.type = type;
this.desc = desc;
}
public String getType() {
return type;
}
public String getDesc() {
return desc;
}
}
- 日志注解切面
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class LogAspect {
private final MessagePublisher messagePublisher;
/** 排除敏感属性字段 */
public static final String[] EXCLUDE_PROPERTIES = { "password", "oldPassword", "newPassword", "confirmPassword" };
/**
* 处理完请求后执行
*
* @param joinPoint 切点
*/
@AfterReturning(pointcut = "@annotation(log)", returning = "result")
public void doAfterReturning(JoinPoint joinPoint, Log log, Object result) {
handleLog(joinPoint, log, null, result);
}
/**
* 拦截异常操作
*
* @param joinPoint 切点
* @param e 异常
*/
@AfterThrowing(value = "@annotation(log)", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Log log, Exception e) {
handleLog(joinPoint, log, e, null);
}
protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
try {
// 获取当前的用户
IUser loginUser = UserThreadLocal.get();
SysLogBo sysLogBo = new SysLogBo();
sysLogBo.setStatus(StatusEnum.SUCCESS.getStatus());
// 请求的地址
String ip = NetWorkUtil.getIpAddr(HttpServletUtil.getRequest());
sysLogBo.setIp(ip);
sysLogBo.setUrl(StringUtils.substring(HttpServletUtil.getRequest().getRequestURI(), 0, 255));
if (loginUser != null) {
sysLogBo.setOperatorName(loginUser.getUsername());
}
if (e != null) {
sysLogBo.setStatus(StatusEnum.FAIL.getStatus());
sysLogBo.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
}
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
sysLogBo.setMethod(className + "." + methodName + "()");
// 设置请求方式
sysLogBo.setRequestMethod(HttpServletUtil.getRequest().getMethod());
// 处理设置注解上的参数
getControllerMethodDescription(joinPoint, controllerLog, sysLogBo, jsonResult);
//发生消息
messagePublisher.publishMessage("yyou-log",GsonUtil.bean2json(sysLogBo));
} catch (Exception exp) {
// 记录本地异常日志
log.error("异常信息:{}", exp.getMessage());
exp.printStackTrace();
}
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解
*
* @param log 日志
* @param sysLogBo 操作日志
* @throws Exception
*/
public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysLogBo sysLogBo, Object jsonResult) throws Exception {
// 设置action动作
sysLogBo.setOperationType(log.operationType().name());
// 设置操作人类别
sysLogBo.setModuleName(log.moduleName().getDesc());
// 是否需要保存request,参数和值
if (log.isSaveRequestData()) {
// 获取参数的信息,传入到数据库中。
setRequestValue(joinPoint, sysLogBo);
}
// 是否需要保存response,参数和值
if (log.isSaveResponseData() && Objects.nonNull(jsonResult)) {
sysLogBo.setResult(StringUtils.substring(JSON.toJSONString(jsonResult), 0, 2000));
}
}
/**
* 获取请求的参数,放到log中
*
* @param sysLogBo 操作日志
* @throws Exception 异常
*/
private void setRequestValue(JoinPoint joinPoint, SysLogBo sysLogBo) throws Exception {
String requestMethod = sysLogBo.getRequestMethod();
if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
String params = argsArrayToString(joinPoint.getArgs());
sysLogBo.setParam(StringUtils.substring(params, 0, 2000));
} else {
Map<?, ?> paramsMap = HttpServletUtil.getParamMap(HttpServletUtil.getRequest());
sysLogBo.setParam(StringUtils.substring(JSON.toJSONString(paramsMap, excludePropertyPreFilter()), 0, 2000));
}
}
/**
* 参数拼装
*/
private String argsArrayToString(Object[] paramsArray) {
String params = "";
if (paramsArray != null && paramsArray.length > 0) {
for (Object o : paramsArray) {
if (Objects.nonNull(o) && !isFilterObject(o)) {
try {
String jsonObj = JSON.toJSONString(o, excludePropertyPreFilter());
params += jsonObj.toString() + " ";
} catch (Exception e) {
}
}
}
}
return params.trim();
}
/**
* 忽略敏感属性
*/
public PropertyPreExcludeFilter excludePropertyPreFilter() {
return new PropertyPreExcludeFilter().addExcludes(EXCLUDE_PROPERTIES);
}
/**
* 判断是否需要过滤的对象。
*
* @param o 对象信息。
* @return 如果是需要过滤的对象,则返回true;否则返回false。
*/
@SuppressWarnings("rawtypes")
public boolean isFilterObject(final Object o) {
Class<?> clazz = o.getClass();
if (clazz.isArray()) {
return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
} else if (Collection.class.isAssignableFrom(clazz)) {
Collection collection = (Collection) o;
for (Object value : collection) {
return value instanceof MultipartFile;
}
} else if (Map.class.isAssignableFrom(clazz)) {
Map map = (Map) o;
for (Object value : map.entrySet()) {
Map.Entry entry = (Map.Entry) value;
return entry.getValue() instanceof MultipartFile;
}
}
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
|| o instanceof BindingResult;
}
}
- Redis消息生产者服务
@Component
public class MessagePublisher {
private final RedisTemplate<String, String> redisTemplate;
public MessagePublisher(RedisTemplate<String, String> redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void publishMessage(String topic,String message) {
redisTemplate.convertAndSend(topic, message);
}
}
- Redis消息配置
@Configuration
public class RedisMessageConfig {
@Bean
public ChannelTopic topic() {
return new ChannelTopic("yyou-log"); // 定义消息队列的通道名称
}
@Bean
public MessageListenerAdapter messageListenerAdapter(MessageConsumer messageConsumer) {
return new MessageListenerAdapter(messageConsumer);
}
@Bean
public RedisMessageListenerContainer redisContainer(RedisConnectionFactory redisConnectionFactory,
MessageListenerAdapter messageListenerAdapter,
ChannelTopic topic) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnectionFactory);
container.addMessageListener(messageListenerAdapter, topic);
return container;
}
}
- Redis消息消费者服务
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class MessageConsumer implements MessageListener {
private final SysLogService sysLogService;
@Override
public void onMessage(Message message, byte[] pattern) {
String data = message.toString();
log.info("Received message: " + data);
sysLogService.add(GsonUtil.json2bean(data, SysLogBo.class));
}
}