博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot使用AOP做系统日志
阅读量:3956 次
发布时间:2019-05-24

本文共 5014 字,大约阅读时间需要 16 分钟。

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

SpringBoot使用AOP做系统日志

目录

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

org.springframework.boot
spring-boot-starter-aop

2.自定义一个注解类LoggerSystem

import java.lang.annotation.*;@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface LoggerSystem {    String value() default "";}

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

@Component@Aspectpublic 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

@Datapublic 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

转载地址:http://iftzi.baihongyu.com/

你可能感兴趣的文章
C++的4种智能指针剖析使用
查看>>
RPC框架实现之容灾策略
查看>>
Docker私库
查看>>
hdu——1106排序(重定向)
查看>>
hdu——1556Color the ball(树状数组)
查看>>
hdu——1541Stars(树状数组)
查看>>
快速幂的精简代码
查看>>
求大数乘方的前n位数字(对数加快速幂)
查看>>
hdu——2602Bone Collector(第一类背包问题)
查看>>
hdu——1711Number Sequence(kmp专练)
查看>>
strstr函数和find函数的异同
查看>>
Java的反射
查看>>
HTTP请求之POST与GET区别
查看>>
SSM结合Redis
查看>>
优化数据库的八种方法
查看>>
Java Web服务收到请求时线程的情况以及session情况
查看>>
SSM配置文件信息加密实现
查看>>
@Produces注解
查看>>
谈谈序列化—实体bean一定要实现Serializable接口?
查看>>
实用小技巧之电脑如何滚动截屏/截取长图
查看>>