Spring Cloud使用 AOP记录用户操作日志

使用springcloud 和springboot没有多大区别,主要是关于aop的代码要放在公共项目common中,一开始我放在某个业务工程t1中,其他没有依赖t1的工程,都不能使用该log。

该日志的功能: 记录用户每一次的行为的用户ID,使用时间,请求参数,返回结果,模块,请求时长。【将该日志数据存到数据库中,能够让cloud项目所有的controller接口都能使用,不用自定义注解】

使用了环绕通知

=====================================================

代码:

1.日志实体类:

@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class SysLog implements Serializable {

    private Integer id;
    private String username;
    private String operation;
    private String time;
    private String method;
    private String params;
    private String ip;
 //   @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private String createTime;
    private String result;

}

2.获取用户IP地址:

public class IPUtils {
    /**
     * 获取IP地址
     *
     * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
     * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }
}

3.

public class HttpContextUtils {
    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
}

4.正文:

@Slf4j
@Aspect
@Component
public class LogAspects {

 //   @Autowired
 //   private SysLogDao sysLogDao;

//    @Pointcut("@annotation(com.lezhi.course.config.log.Log)")
//    public void pointcut() { }

//    @Around("pointcut()")

    @Around("execution(* com.lezhi.*.controller.*.*(..))")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = point.proceed();
            log.error("返回值为:"+ JSON.toJSONString(result));

        } catch (Throwable e) {
            e.printStackTrace();
        }
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        // 保存日志
        saveLog(point, time,result);
        return result;
    }

    private void saveLog(ProceedingJoinPoint joinPoint, long time,Object result ) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SysLog sysLog = new SysLog();
        Log logAnnotation = method.getAnnotation(Log.class);
//        if (logAnnotation != null) {
//            // 注解上的描述
//            sysLog.setOperation(logAnnotation.value());
//        }
        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");
        // 请求的方法参数值
        Object[] args = joinPoint.getArgs();
        // 请求的方法参数名称
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        if (args != null && paramNames != null) {
            String params = "";
            for (int i = 0; i < args.length; i++) {
                params += "  " + paramNames[i] + ": " + args[i];
            }
            sysLog.setParams(params);
        }
        // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        // 设置IP地址
        sysLog.setIp(IPUtils.getIpAddr(request));
        // 模拟一个用户名
       SecurityUserDetails userDetails = (SecurityUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = Long.parseLong(userDetails.getUsername());
        sysLog.setUserId(userId);
        sysLog.setTime( String.valueOf(time)+"毫秒");
        //设置日期格式   HH:mm:ss中的HH大写为24小时制。HH和hh的差别是前者为24小时制,后者为12小时制
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

           // new Date()为获取当前系统时间
        String dateTime=df.format(new Date());
        sysLog.setCreateTime(dateTime);
        sysLog.setResult( JSON.toJSONString(result));


        log.error("新增的log日志::"+sysLog.toString());
        // 保存系统日志
    //    sysLogDao.saveSysLog(sysLog);
    }


}

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Cloud AOP(面向切面编程)是 Spring Cloud 框架中的一个核心组件,它提供了一种基于切面的编程方式来实现横切关注点的解耦和复用。 AOP 是一种编程范式,它允许开发人员通过将横切关注点从业务逻辑中剥离出来,以模块化的方式来处理通用的横切关注点,例如日志记录、安全性、事务管理等。在 Spring Cloud使用 AOP,您可以通过定义切面和连接点来实现这些功能。 在 Spring Cloud使用 AOP,您需要引入相关的依赖并配置切面和切点。通过在切面中定义通知(advice),您可以指定在程序执行到特定连接点时要执行的代码。常见的通知类型包括前置通知(Before)、后置通知(After)、返回通知(AfterReturning)和异常通知(AfterThrowing)。 以下是一个使用 Spring Cloud AOP 的示例: ```java @Aspect @Component public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void logBefore(JoinPoint joinPoint) { System.out.println("Before method: " + joinPoint.getSignature().getName()); } @After("execution(* com.example.service.*.*(..))") public void logAfter(JoinPoint joinPoint) { System.out.println("After method: " + joinPoint.getSignature().getName()); } @AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result") public void logAfterReturning(JoinPoint joinPoint, Object result) { System.out.println("After returning method: " + joinPoint.getSignature().getName()); } @AfterThrowing(pointcut = "execution(* com.example.service.*.*(..))", throwing = "exception") public void logAfterThrowing(JoinPoint joinPoint, Exception exception) { System.out.println("After throwing method: " + joinPoint.getSignature().getName()); } } ``` 上述示例中,我们定义了一个名为 `LoggingAspect` 的切面,并在切面中定义了四个通知方法。通过 `@Before`、`@After`、`@AfterReturning` 和 `@AfterThrowing` 注解,我们分别实现了前置通知、后置通知、返回通知和异常通知。这些通知方法会在连接点(这里是 `com.example.service` 包下的所有方法)执行前、后、返回和抛出异常时被触发。 需要注意的是,要使 AOP 生效,您还需要在 Spring Cloud 应用程序的配置文件中启用 AOP,例如,在 `application.properties` 中添加以下配置: ``` spring.aop.auto=true ``` 这样,Spring Cloud 应用程序中的相关切面和连接点就会被自动扫描并应用。希望这个简单的示例能帮助您理解 Spring Cloud AOP 的基本用法。如果您有更多问题,请随时提问!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值