记录操作日志注解

/**
 * 根据配置的请求路径记录操作日志
 * */

public ResponseVo<String> save(@Validated(SaveRecord.class) @LogRecord("新增单证") MortgageDocumentRequest mortgageDocumentRequest,
                               @CookieValue(value = "umid", required = false) String umid) {
    mortgageDocumentService.save(mortgageDocumentRequest, umid);
    return new ResponseVo<>("新增成功");
}
package com.paic.phucp.console.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
@Documented
public  @interface LogRecord {

    String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
@Documented
public @interface PrimaryId {
}
package com.paic.phucp.console.aop;

import com.paic.phucp.console.annotations.LogRecord;
import com.paic.phucp.console.annotations.PrimaryId;
import com.paic.phucp.dao.mapper.mmapper.UcpDocWebLogMapper;
import com.paic.phucp.dao.po.UcpDocWebLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Aspect
@Component
public class LogRecordsAop {

    @Value("${log.records.mappings:/mortgage}")
    private String logRecordsMappings;

    @Resource
    private UcpDocWebLogMapper ucpDocWebLogMapper;

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void logRecords() {
        // this is an aop pointcut, don't need do anything
    }

    @AfterReturning("logRecords()")
    public void after(JoinPoint joinPoint) throws Throwable {
        RequestMapping controller = joinPoint.getTarget().getClass().getAnnotation(RequestMapping.class);
        if (null == controller) {
            return ;
        }

        if (controller.value().length == 0) {
            return ;
        }

        List<String> mappings = Arrays.asList(logRecordsMappings.split(","));
        if (!mappings.contains(controller.value()[0])) {
            return ;
        }

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        RequestMapping requestMapping = signature.getMethod().getAnnotation(RequestMapping.class);
        if (null == requestMapping) {
            return ;
        }

        Object[] args = joinPoint.getArgs();

        Annotation[][] parameterAnnotations = signature.getMethod().getParameterAnnotations();
        GetParamValue getParamValue = new GetParamValue(args, parameterAnnotations).invoke();
        Object paramValue = getParamValue.getParamValue();
        LogRecord logRecord = getParamValue.getLogRecord();

        if (paramValue == null) {
            return ;
        }

        Object logPrimary = getPrimaryId(paramValue);

        if (logPrimary == null) {
            return ;
        }

        Object createdBy = getCreatedBy(args, parameterAnnotations);

        saveLog(controller, requestMapping, paramValue, logRecord, logPrimary, createdBy);
    }

    private class GetParamValue {
        private Object[] args;
        private Annotation[][] parameterAnnotations;
        private Object paramValue;
        private LogRecord logRecord;

        GetParamValue(Object[] args, Annotation[]... parameterAnnotations) {
            this.args = args;
            this.parameterAnnotations = parameterAnnotations;
        }

        Object getParamValue() {
            return paramValue;
        }

        LogRecord getLogRecord() {
            return logRecord;
        }

        public GetParamValue invoke() {
            paramValue = null;
            logRecord = null;
            for (Annotation[] parameterAnnotation : parameterAnnotations) {
                int paramIndex = ArrayUtils.indexOf(parameterAnnotations, parameterAnnotation);
                for (Annotation annotation : parameterAnnotation) {
                    if (annotation instanceof LogRecord) {
                        logRecord = (LogRecord) annotation;
                        paramValue = args[paramIndex];
                        break;
                    }
                }
                if (null != paramValue) {
                    break;
                }
            }
            return this;
        }
    }

    private Object getPrimaryId(Object paramValue) throws IllegalAccessException {
        Field[] fields = paramValue.getClass().getDeclaredFields();
        Object logPrimary = null;
        for (Field field : fields) {
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            PrimaryId annotation = field.getAnnotation(PrimaryId.class);
            if (null != annotation) {
                logPrimary = field.get(paramValue);
                break;
            }
        }
        return logPrimary;
    }

    private Object getCreatedBy(Object[] args, Annotation[][] parameterAnnotations) {
        Object createdBy = null;
        for (Annotation[] parameterAnnotation : parameterAnnotations) {
            int paramIndex = ArrayUtils.indexOf(parameterAnnotations, parameterAnnotation);
            for (Annotation annotation : parameterAnnotation) {
                if (annotation instanceof CookieValue) {
                    createdBy = args[paramIndex];
                    break;
                }
            }
            if (null != createdBy) {
                break;
            }
        }
        return createdBy;
    }

    private void saveLog(RequestMapping controller, RequestMapping requestMapping, Object paramValue, LogRecord logRecord, Object logPrimary, Object createdBy) {
        byte[] bytes = new Base64().encode(paramValue.toString().getBytes());
        UcpDocWebLog log = new UcpDocWebLog();
        log.setLogPrimary(logPrimary == null ? "" : logPrimary.toString());
        log.setCreatedBy(createdBy == null ? "" : createdBy.toString());
        log.setUpdatedBy(createdBy == null ? "" : createdBy.toString());
        log.setCreatedDate(new Date());
        log.setUpdatedDate(new Date());
        log.setRemark(logRecord.value());
        log.setRequestParams(new String(bytes, Charset.defaultCharset()));
        log.setWebAddress(controller.value()[0] + requestMapping.value()[0]);
        ucpDocWebLogMapper.insert(log);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个使用拦截器记录操作日志的实现代码示例: ```java @Component @Aspect public class LogInterceptor { private static final Logger LOGGER = LoggerFactory.getLogger(LogInterceptor.class); @Autowired private LogService logService; @Autowired private HttpServletRequest request; @Pointcut("execution(* com.example.controller.*.*(..))") public void pointCut() {} @Before("pointCut()") public void doBefore(JoinPoint joinPoint) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { username = "anonymous"; } String methodName = joinPoint.getSignature().getName(); String className = joinPoint.getTarget().getClass().getSimpleName(); String params = Arrays.toString(joinPoint.getArgs()); LOGGER.info("User {} accessed {}.{}, with parameters {}", username, className, methodName, params); } @AfterReturning(pointcut = "pointCut()", returning = "returnValue") public void doAfterReturning(JoinPoint joinPoint, Object returnValue) { String username = (String) request.getSession().getAttribute("username"); if (username == null) { username = "anonymous"; } String methodName = joinPoint.getSignature().getName(); String className = joinPoint.getTarget().getClass().getSimpleName(); String params = Arrays.toString(joinPoint.getArgs()); String returnValueString = returnValue == null ? "" : returnValue.toString(); LOGGER.info("User {} accessed {}.{}, with parameters {}, and returned value {}", username, className, methodName, params, returnValueString); // 保存操作日志到数据库 Log log = new Log(); log.setUsername(username); log.setClassName(className); log.setMethodName(methodName); log.setParams(params); log.setReturnValue(returnValueString); logService.save(log); } } ``` 这是一个使用 Spring AOP 实现的拦截器,通过 @Pointcut 注解指定需要拦截的方法,然后在方法执行前和执行后分别记录日志和保存操作日志到数据库中。其中,日志记录使用了 slf4j + logback 的组合,可以根据需要进行配置。 需要注意的是,这里使用了 HttpServletRequest 对象获取当前用户的信息,如果你的项目中没有使用 Spring MVC 或者类似的框架,可以通过其他方式获取用户信息。此外,这里的 LogService 是一个自定义的服务类,需要根据自己的实际情况进行定义和实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值