SpringBoot使用AOP做系统日志

你未必出类拔萃,但一定与众不同

SpringBoot使用AOP做系统日志

1.在项目中导入相关的依赖AOP

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2.自定义一个注解类LoggerSystem

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoggerSystem {
    String value() default "";
}

3.对系统日志做切面处理

@Component
@Aspect
public class LoggerSystemAspect {

    /**
     * 注入日志的服务
     */
    @Autowired
    private SysLogService sysLogService;
    /**
     * 此处定义切点@Poincut
     * 在有LoggerSystem注解的地方进行代码切入
     */
    @Pointcut("@annotation( com.bluedot.zpapp.annotation.LoggerSystem)")
    public void loggerPointCut(){

    }

    @AfterReturning("loggerPointCut()")
    public void saveLog(JoinPoint joinPoint){
        //创建自定义日志对象
        ZpSysLog zpSysLog = new ZpSysLog();

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();
        //此处获取注解方法
        LoggerSystem loggerSystem = method.getAnnotation(LoggerSystem.class);
        if (loggerSystem != null) {
            String value = loggerSystem.value();
            //将当前注解中注解的功能说明塞入日志对象中
            zpSysLog.setLoggerOperation(value);
        }
        //获取请求的类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取请求的方法名
        String methodName = method.getName();
        zpSysLog.setLoggerMethod(className + "." + methodName);

        //请求的参数
        Object[] args = joinPoint.getArgs();
        //将参数所在的数组转换成json
        String params = JSON.toJSONString(args);
        zpSysLog.setLoggerParams(params);

        zpSysLog.setLoggerDate(GetDateUtil.getDateTime());
        /**
         * 因为当前项目采用shiro作为用户认证和校验的框架
         * 通过获取shiro中的当前用户的电话号作为日志对象中的值
         */
        zpSysLog.setLoggerUsername(ShiroUtils.getUser().getUserPhone());
        //获取用户ip地址
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        zpSysLog.setLoggerIp(IPUtils.getIPAddress(request));
        //调用service保存SysLog实体类到数据库
        sysLogService.insertLog(zpSysLog);
    }
}

4.使用自身定义的系统日志进行操作 登录为例子

以下只提供部分代码

在当前toLogin的接口上写入注解@LoggerSystem(value = “用户登录”)进行使用

/**
     * 登录api
     * @param userPhone
     * @param userPass
     * @return
     */
    @RequestMapping("/userLogin")
    @LoggerSystem(value = "用户登录")
    @ResponseBody
    public ResultMap toLogin(@RequestParam(value = "userPhone")String userPhone,
                             @RequestParam(value = "userPass")String userPass){
        ResultMap map = new ResultMap();
        ZpUserList zpUserList = new ZpUserList();
        zpUserList = userService.queryUserInfo(userPhone);
        //1.获取Subject
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userPhone, userPass);

5.运行后数据库结果

在这里插入图片描述

6.其他相关的类

实体类ZpSysLog

@Data
public class ZpSysLog implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * id
     */
    private Long loggerId;

    /**
     * 用户名
     */
    private String loggerUsername;

    /**
     * 操作
     */
    private String loggerOperation;

    /**
     * 方法名
     */
    private String loggerMethod;

    /**
     * 参数
     */
    private String loggerParams;

    /**
     * ip地址
     */
    private String loggerIp;

    /**
     * 操作时间
     */
    private Date loggerDate;

    public ZpSysLog() {
    }

}

shiro的工具类ShiroUtils

public class ShiroUtils {
    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    /**获取shiro的连接器*/
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**获取登录用户的信息*/
    public static ZpUserList getUser() {
        return (ZpUserList) SecurityUtils.getSubject().getPrincipal();
    }

    /**获取登录用户的id*/
    public static String getUserId() {
        return getUser().getUserPhone();
    }

    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    /**用于判断有没有获取登录用户的信息*/
    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }
    /**注销用户*/
    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    public static String getKaptcha(String key) {
        String kaptcha = getSessionAttribute(key).toString();
        getSession().removeAttribute(key);
        return kaptcha;
    }
}

日志系统表创建语句

CREATE TABLE `zp_sys_log` (
  `logger_id` bigint(10) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `logger_username` varchar(100) DEFAULT NULL COMMENT '用户名',
  `logger_operation` varchar(100) DEFAULT NULL COMMENT '操作',
  `logger_method` varchar(200) DEFAULT NULL COMMENT '方法名',
  `logger_params` varchar(500) DEFAULT NULL COMMENT '参数',
  `logger_ip` varchar(50) DEFAULT NULL COMMENT 'ip地址',
  `logger_date` datetime DEFAULT NULL COMMENT '操作时间',
  PRIMARY KEY (`logger_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鱼爱吃柚子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值