1.引入AOP依赖

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

2.创建日志记录表

DROP TABLE IF EXISTS `rule_operate_log`;
CREATE TABLE `rule_operate_log`  (
    id INT(11) NOT NULL AUTO_INCREMENT COMMENT '日志id',
    path VARCHAR(4000) NULL DEFAULT NULL COMMENT '接口地址',
    http_method VARCHAR(32) NULL DEFAULT NULL COMMENT '请求方法',
    status_code VARCHAR(32) NULL DEFAULT NULL COMMENT '请求返回状态码',
    create_time_char VARCHAR(32) NULL DEFAULT NULL COMMENT '日志时间',
    create_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '日志时间戳',
    ip varchar(200) NULL DEFAULT NULL COMMENT '请求ip',
    params mediumtext NULL COMMENT '请求参数',
    result mediumtext NULL COMMENT '返回值',
    exception mediumtext NULL COMMENT '接口异常',
    user_id VARCHAR(32) NULL DEFAULT NULL COMMENT '操作用户',
    user_account VARCHAR(32) NULL DEFAULT NULL COMMENT '操作用户账号',
    user_name VARCHAR(200) NULL DEFAULT NULL COMMENT '操作用户名称',
    user_org_id VARCHAR(32) NULL DEFAULT NULL COMMENT '操作用户机构id',
    user_org_name VARCHAR(200) NULL DEFAULT NULL COMMENT '操作用户机构名称',
    operate_name VARCHAR(200) NULL DEFAULT NULL COMMENT '操作名称',
    operate_position VARCHAR(200) NULL DEFAULT NULL COMMENT '操作位置',
    log_type VARCHAR(32) NULL DEFAULT NULL COMMENT '日志类型 error:错误日志 operate:操作日志',
    category_id VARCHAR(32) NULL DEFAULT NULL COMMENT '分类机构id',
    cost INT(11) NULL DEFAULT NULL COMMENT '接口耗时',
    PRIMARY KEY (id)
) COMMENT = '操作日志表';

3.日志实体类

import java.util.Date;

public class RuleOperateLog {
    /**
     * id
     */
    private Integer id;
    /**
     * 接口地址
     */
    private String path;
    /**
     * 请求方法
     */
    private String httpMethod;
    /**
     * 请求返回状态码
     */
    private String statusCode;
    /**
     * 日志时间
     */
    private String createTimeChar;
    /**
     * 日志时间戳
     */
    private Date createTime;
    /**
     * 请求ip
     */
    private String ip;
    /**
     * 请求参数
     */
    private String params;
    /**
     * 返回值
     */
    private String result;
    /**
     * 接口异常
     */
    private String exception;
    /**
     * 操作用户
     */
    private String userId;
    /**
     * 操作用户账号
     */
    private String userAccount;
    /**
     * 操作用户名称
     */
    private String userName;
    /**
     * 操作用户机构
     */
    private String userOrgId;
    /**
     * 操作用户机构名称
     */
    private String userOrgName;
    /**
     * 操作名称
     */
    private String operateName;
    /**
     * 操作位置
     */
    private String operatePosition;
    /**
     * 日志类型
     */
    private String logType;
    /**
     * 分类机构id
     */
    private String categoryId;
    /**
     * 请求耗时
     */
    private Integer cost;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getHttpMethod() {
        return httpMethod;
    }

    public void setHttpMethod(String httpMethod) {
        this.httpMethod = httpMethod;
    }

    public String getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(String statusCode) {
        this.statusCode = statusCode;
    }

    public String getCreateTimeChar() {
        return createTimeChar;
    }

    public void setCreateTimeChar(String createTimeChar) {
        this.createTimeChar = createTimeChar;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getParams() {
        return params;
    }

    public void setParams(String params) {
        this.params = params;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getException() {
        return exception;
    }

    public void setException(String exception) {
        this.exception = exception;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserAccount() {
        return userAccount;
    }

    public void setUserAccount(String userAccount) {
        this.userAccount = userAccount;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserOrgId() {
        return userOrgId;
    }

    public void setUserOrgId(String userOrgId) {
        this.userOrgId = userOrgId;
    }

    public String getUserOrgName() {
        return userOrgName;
    }

    public void setUserOrgName(String userOrgName) {
        this.userOrgName = userOrgName;
    }

    public String getOperateName() {
        return operateName;
    }

    public void setOperateName(String operateName) {
        this.operateName = operateName;
    }

    public String getOperatePosition() {
        return operatePosition;
    }

    public void setOperatePosition(String operatePosition) {
        this.operatePosition = operatePosition;
    }

    public String getLogType() {
        return logType;
    }

    public void setLogType(String logType) {
        this.logType = logType;
    }

    public String getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(String categoryId) {
        this.categoryId = categoryId;
    }

    public Integer getCost() {
        return cost;
    }

    public void setCost(Integer cost) {
        this.cost = cost;
    }
}

4.Dao Mapper service

import com.xxx.xxx.xxx.entity.RuleOperateLog;

/**
 * 操作日志(RuleOperateLog)表数据库访问层
 *
 * @author hx
 * @since 2022-08-23
 */
public interface RuleOperateLogDao {

    /**
     * 新增数据
     *
     * @param operateLog
     * @return
     */
    int insert(RuleOperateLog operateLog);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxx.xxx.xxx.dao.RuleOperateLogDao">

    <resultMap type="com.xxx.xxx.xxx.entity.RuleOperateLog" id="RuleOperateLogMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="path" column="path" jdbcType="VARCHAR"/>
        <result property="httpMethod" column="http_method" jdbcType="VARCHAR"/>
        <result property="statusCode" column="status_code" jdbcType="VARCHAR"/>
        <result property="createTimeChar" column="create_time_char" jdbcType="VARCHAR"/>
        <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
        <result property="ip" column="ip" jdbcType="VARCHAR"/>
        <result property="params" column="params" jdbcType="VARCHAR"/>
        <result property="result" column="result" jdbcType="VARCHAR"/>
        <result property="exception" column="exception" jdbcType="VARCHAR"/>
        <result property="userId" column="user_id" jdbcType="VARCHAR"/>
        <result property="userAccount" column="user_account" jdbcType="VARCHAR"/>
        <result property="userName" column="user_name" jdbcType="VARCHAR"/>
        <result property="userOrgId" column="user_org_id" jdbcType="VARCHAR"/>
        <result property="userOrgName" column="user_org_name" jdbcType="VARCHAR"/>
        <result property="operateName" column="operate_name" jdbcType="VARCHAR"/>
        <result property="operatePosition" column="operate_position" jdbcType="VARCHAR"/>
        <result property="logType" column="log_type" jdbcType="VARCHAR"/>
        <result property="categoryId" column="category_id" jdbcType="VARCHAR"/>
        <result property="cost" column="cost" jdbcType="INTEGER"/>
    </resultMap>

    <insert id="insert" keyProperty="id" useGeneratedKeys="true">
        insert into rule_operate_log (id, path, http_method, status_code, create_time_char, create_time,
                                      ip, params, result, exception, user_id, user_account, user_name, user_org_id,
                                      user_org_name, operate_name, operate_position, log_type, category_id, cost)
        values (#{id}, #{path}, #{httpMethod}, #{statusCode}, #{createTimeChar}, #{createTime}, #{ip}, #{params}, #{result},
                #{exception},#{userId}, #{userAccount}, #{userName}, #{userOrgId}, #{userOrgName}, #{operateName}, #{operatePosition},
                #{logType}, #{categoryId}, #{cost})
    </insert>

</mapper>
import com.xxx.xxx.xxx.entity.RuleOperateLog;

/**
 * 操作日志(RuleOperateLog)表服务接口
 *
 * @author hx
 * @since 2022-08-23
 */
public interface RuleOperateLogService {

    /**
     * 保存日志
     *
     * @param ruleOperateLog
     * @return
     */
    void saveLog(RuleOperateLog ruleOperateLog);

}
import com.xxx.xxx.xxx.dao.RuleOperateLogDao;
import com.xxx.xxx.xxx.entity.RuleOperateLog;
import com.xxx.xxx.xxx.service.RuleOperateLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 操作日志(RuleOperateLog)表服务实现类
 *
 * @author hx
 * @since 2022-08-23
 */
@Service("RuleOperateLogService")
public class RuleOperateLogServiceImpl implements RuleOperateLogService {

    @Autowired
    private RuleOperateLogDao operateLogDao;

    @Override
    public void saveLog(RuleOperateLog ruleOperateLog) {
        operateLogDao.insert(ruleOperateLog);
    }
}

5.自定义注解

import java.lang.annotation.*;

@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface LogResource {
    /**
     * 服务名称
     * @return
     */
    String name();

    /**
     * 操作位置描述
     * @return
     */
    String position() default "";

    /**
     * 日志类型
     * @return
     */
    String logType() default "";
}

6.操作日志切面类

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.com.xxx.xxx.xxx.annotation.LogResource;
import com.com.xxx.xxx.xxx.constants.LogTypeConstants;
import com.com.xxx.xxx.xxx.entity.RuleOperateLog;
import com.com.xxx.xxx.xxx.service.RuleOperateLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 操作日志切面类
 *
 * @author hx
 * @since 2022-08-23
 */

@Aspect
@Component
public class OperateLogAspect {

    @Autowired
    private RuleOperateLogService operateLogService;

    //扫描使用@LogResource注解的方法
    @Pointcut("@annotation(com.com.xxx.xxx.xxx.annotation.LogResource)")
    public void logPointCut() { };

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Date startTime = new Date();
        String exception = null;
        String result = null;
        try {
            Object obj = point.proceed();
            if (obj != null) {
                result = JSONObject.toJSONString(obj);
            }
            return obj;
        } catch (Exception e) {
            //请求时报错
            exception = e.toString();
            throw e;
        } finally {
            //操作和报错日志都记录
            HttpServletResponse response
                    = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            int statusCode = response.getStatus();
            if (exception != null) {
                /** CHECKSTYLE:OFF:MagicNumber */
                statusCode = 500;
                /** CHECKSTYLE:ON:MagicNumber */
            }
            syncSaveLog(point, startTime, new Date(), exception, result, statusCode);
        }
    }

    @Async
    void syncSaveLog(ProceedingJoinPoint joinPoint, Date startTime, Date endTime,
                     String exception, String result, int statusCode) {
        RuleOperateLog log = new RuleOperateLog();
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            LogResource annotation = method.getAnnotation(LogResource.class);
            if (annotation != null) {
                //注解上的描述
                log.setOperateName(annotation.name());
            }
            Date nowDate = new Date();
            log.setCreateTimeChar(new SimpleDateFormat("yyyyMMddhhmmss").format(nowDate));
            log.setCreateTime(nowDate);
            //入参
            if (joinPoint.getArgs() != null) {
                try {
                    log.setParams(JSONObject.toJSONString(joinPoint.getArgs(),
                            SerializerFeature.IgnoreNonFieldGetter));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            Long cost = endTime.getTime() - startTime.getTime();
            log.setCost(cost.intValue());
            HttpServletRequest request
                    = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            if (request != null) {
                log.setUserName(request.getHeader(HttpHeaders.USER_AGENT));
                log.setPath(request.getRequestURI());
                log.setHttpMethod(request.getMethod());
                log.setIp(request.getRemoteAddr());
            }
            log.setStatusCode(String.valueOf(statusCode));
            log.setResult(result);
            /** CHECKSTYLE:OFF:MagicNumber */
            if (statusCode > 400 && exception != null) {
                log.setException(exception);
                log.setLogType(LogTypeConstants.ERROR);
            } else {
                log.setLogType(LogTypeConstants.OPERATE);
            }
            /** CHECKSTYLE:ON:MagicNumber */
            operateLogService.saveLog(log);
        } catch (Exception e) {
            e.printStackTrace();
        }

/*        //启动一个线程,执行报错日志防止影响主请求
        new Thread() {
            @Override
            public void run() {
                try {
                    //保存到数据库
                    operLogMapper.insertOper(operLog);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();*/
    }
}

7.使用

到此这篇关于Spring AOP实现接口请求记录到数据库的文章就介绍到这了,更多相关Spring AOP接口请求记录数据库内容请搜索Devmax以前的文章或继续浏览下面的相关文章希望大家以后多多支持Devmax!

Spring AOP实现接口请求记录到数据库的示例代码的更多相关文章

  1. 详解前端HTML5几种存储方式的总结

    本篇文章主要介绍了前端HTML5几种存储方式的总结 ,主要包括本地存储localstorage,本地存储sessionstorage,离线缓存(application cache),Web SQL,IndexedDB。有兴趣的可以了解一下。

  2. PhoneGap / iOS上的SQLite数据库 – 超过5mb可能

    我误解了什么吗?Phonegap中的sqlitedbs真的有5mb的限制吗?我正在使用Phonegap1.2和iOS5.解决方法您可以使用带有phonegap插件的原生sqliteDB,您将没有任何限制.在iOS5.1中,Websql被认为是可以随时删除的临时数据…

  3. ios – 领域:如何获取数据库的当前大小

    是否有RealmAPI方法使用RealmSwift作为数据存储来获取我的RealmSwift应用程序的当前数据库大小?

  4. ios – Realm – 无法使用现有主键值创建对象

    我有一个对象有许多狗的人.应用程序有单独的页面,它只显示狗和其他页面显示人的狗我的模型如下我有人存储在Realm中.人有详细页面,我们取,并显示他的狗.如果狗已经存在,我会更新该狗的最新信息并将其添加到人的狗列表中,否则创建新狗,保存并将其添加到人员列表中.这适用于coredata.在尝试用他的狗更新人时,领域会抛出异常无法使用现有主键值创建对象解决方法这里的问题是,即使你正在创建一个全新的Rea

  5. ios – UIWebView中的WebSQL / SQLite数据库的最大大小(phonegap)

    我知道一般来说,Web应用程序的本地存储空间有5MB的限制.本地网页浏览应用程式是否也有这个限制?

  6. ios – Firebase离线存储高级 – 手动同步和进度信息

    >我可以提供一个捆绑数据库–安装App后我可以已经离线查询了Firebase数据?然后我有另一个关于Firebase的主要问题:>JSON存储是伟大的–但是这样我们不关心一个独特的结构,我们必须注意这一点插入总是正确的数据集?我从来没有试图显示实际的进展,但是当您从firebase中检索数据时,始终会在成功检索数据时调用onDataChange方法.https://firebase.google.com/docs/database/android/retrieve-data#read_data_onceC

  7. ios – 如何处理多用户数据库

    我的应用程序就像很多应用程序–它有一个用户输入用户名和密码的登录屏幕,以及登录按钮我的应用程序还使用CoreData来保存大多数用户的业务对象,当然也是用户特定的.我也有一个登出按钮来启用切换用户.这不会发生很多,但仍然是必要的).现在如果不同的用户登录,我需要获取他的具体数据.但是我该如何做呢?

  8. ios – Swift从Firebase数据库中获取特定价值

    我正在尝试从Firebase数据库中获取特定值.我看了一些像谷歌这样的文件,但我做不到.这是数据库的JSON文件:SWIFT代码:我想获得用户的电子邮件价值,而不是每个人.我怎样才能做到这一点?解决方法在您的代码中,快照将包含子值的字典.要访问它们,请将snapshot.value转换为Dictionary,然后访问各个子项是一个快照

  9. ios – Realm Swift:在卸载应用程序后是否可以保留数据库?

    使用realmswift,即使从设备上卸载应用程序,是否可以在设备内存中保留和维护应用程序的领域数据库文件?非常感谢您的帮助.解决方法删除应用程序时,应用程序的所有文件都是剩余的.iOS应用程序是沙盒.这意味着每个应用程序在磁盘中都有自己的空间,并有自己的目录,这些目录充当应用程序及其数据的主页.从iPhone删除应用程序会删除此沙箱,删除与该应用程序关联的所有数据.

  10. ios – 在没有XML的情况下更新sqlite数据库

    我的应用程序需要来自sqlite数据库的数据.它将附带此数据库的一个版本,但我需要定期更新它(很可能每月一次).通常情况下,我一直在通过我设置的一堆网络服务将我的应用程序的其他部分的更新作为XML发送,但我现在正在处理的这个特定数据库非常大(大约20-30MB),而且我当我尝试以这种方式发送时出现超时错误.我尝试将数据库放在我的公司服务器上,然后将其下载到NSData对象中.然后我将该数据对象保存

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部