经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
SpringBoot利用AOP实现一个日志管理详解
来源:jb51  时间:2022/9/20 9:28:45  对本文有异议

1. 需求

目前有这么个问题,有两个系统CSP和OMS,这俩系统共用的是同一套日志操作:Log;目前想区分下这俩系统的日志操作,那没办法了,只能重写一份Log的日志操作;

你也可以参照若依框架的日志系统实现。

2. 新建一张日志表

sys_oper_csp_log

  1. /*
  2. Navicat Premium Data Transfer
  3.  
  4. Source Server : jp-csc-admin
  5. Source Server Type : MySQL
  6. Source Server Version : 50728
  7. Source Host : rm-uf6miy84gu8u433x9.mysql.rds.aliyuncs.com:3306
  8. Source Schema : jp_oms
  9.  
  10. Target Server Type : MySQL
  11. Target Server Version : 50728
  12. File Encoding : 65001
  13.  
  14. Date: 08/09/2022 09:21:45
  15. */
  16.  
  17. SET NAMES utf8mb4;
  18. SET FOREIGN_KEY_CHECKS = 0;
  19.  
  20. -- ----------------------------
  21. -- Table structure for sys_oper_csp_log
  22. -- ----------------------------
  23. DROP TABLE IF EXISTS `sys_oper_csp_log`;
  24. CREATE TABLE `sys_oper_csp_log` (
  25. `oper_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '日志主键',
  26. `title` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '模块标题',
  27. `business_type` int(2) NULL DEFAULT 0 COMMENT '业务类型(0=其它,1=新增,2=修改,3=删除,4=授权,5=导出,6=导入,7=强退,8=生成代码,9=清空数据)',
  28. `method` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '方法名称',
  29. `request_method` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '请求方式',
  30. `operator_type` int(1) NULL DEFAULT 0 COMMENT '操作类别(0其它 1后台用户 2手机端用户)',
  31. `oper_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '操作人员',
  32. `dept_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '部门名称',
  33. `oper_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '请求URL',
  34. `oper_ip` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '主机地址',
  35. `oper_location` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '操作地点',
  36. `oper_param` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '请求参数',
  37. `json_result` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '返回参数',
  38. `status` int(1) NULL DEFAULT 0 COMMENT '操作状态(0正常 1异常)',
  39. `error_msg` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '错误消息',
  40. `oper_time` datetime NULL DEFAULT NULL COMMENT '操作时间',
  41. PRIMARY KEY (`oper_id`) USING BTREE,
  42. INDEX `idx_time`(`oper_time`, `title`, `oper_name`) USING BTREE
  43. ) ENGINE = InnoD CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = 'CSP系统操作日志记录';

3. 写相应的Controller层

  1. package com.juepeiscm.csp.controller.csplog;
  2.  
  3. import com.juepeiscm.admin.api.domain.SysOperLog;
  4. import com.juepeiscm.common.core.controller.BaseController;
  5. import com.juepeiscm.common.core.domain.AjaxResult;
  6. import com.juepeiscm.common.core.page.TableDataInfo;
  7. import com.juepeiscm.common.enums.BusinessType;
  8. import com.juepeiscm.common.utils.poi.ExcelUtil;
  9. import com.juepeiscm.csp.annotation.CspLog;
  10. import com.juepeiscm.csp.domain.csplog.SysOperCspLog;
  11. import com.juepeiscm.csp.service.csplog.ISysOperCspLogService;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.security.access.prepost.PreAuthorize;
  14. import org.springframework.web.bind.annotation.*;
  15.  
  16. import java.util.List;
  17.  
  18. /**
  19. * 操作CSP系统日志
  20. * @Author: py.sun
  21. * @Date: 2022/9/7 14:51
  22. */
  23. @RestController
  24. @RequestMapping({"/csplog/opercsplog"})
  25. public class SysOperCsplogController extends BaseController {
  26. @Autowired
  27. private ISysOperCspLogService operCspLogService;
  28.  
  29. public SysOperCsplogController() {
  30. }
  31.  
  32. /**
  33. * 查询操作日志列表
  34. * @param sysOperCspLog
  35. * @return
  36. */
  37. @PreAuthorize("@ss.hasPermi('monitor:operlog:list')")
  38. @GetMapping({"/list"})
  39. public TableDataInfo list(SysOperCspLog sysOperCspLog) {
  40. this.startPage();
  41. List<SysOperCspLog> list = this.operCspLogService.selectOperLogList(sysOperCspLog);
  42. return this.getDataTable(list);
  43. }
  44.  
  45. /**
  46. * 查询系统模块的分类
  47. * @param
  48. * @return
  49. */
  50. @GetMapping({"/listTitle"})
  51. public TableDataInfo listTitle() {
  52. this.startPage();
  53. List<String> list = this.operCspLogService.selectOperLogListTitle();
  54. return this.getDataTable(list);
  55. }
  56.  
  57. @CspLog(
  58. title = "导出CSP系统日志",
  59. businessType = BusinessType.EXPORT
  60. )
  61. @PreAuthorize("@ss.hasPermi('monitor:operlog:export')")
  62. @GetMapping({"/export"})
  63. public AjaxResult export(SysOperCspLog operLog) {
  64. List<SysOperCspLog> list = this.operCspLogService.selectOperLogList(operLog);
  65. ExcelUtil<SysOperCspLog> util = new ExcelUtil(SysOperLog.class);
  66. return util.exportExcel(list, "操作CSP系统日志");
  67. }
  68.  
  69. @CspLog(
  70. title = "操作CSP系统日志",
  71. businessType = BusinessType.DELETE
  72. )
  73. @PreAuthorize("@ss.hasPermi('monitor:operlog:remove')")
  74. @DeleteMapping({"/{operIds}"})
  75. public AjaxResult remove(@PathVariable Long[] operIds) {
  76. return this.toAjax(this.operCspLogService.deleteOperLogByIds(operIds));
  77. }
  78.  
  79. @CspLog(
  80. title = "清除CSP系统日志",
  81. businessType = BusinessType.CLEAN
  82. )
  83. @PreAuthorize("@ss.hasPermi('monitor:operlog:remove')")
  84. @DeleteMapping({"/clean"})
  85. public AjaxResult clean() {
  86. this.operCspLogService.cleanOperLog();
  87. return AjaxResult.success();
  88. }
  89.  
  90.  
  91. }

4.Service接口层

  1. package com.juepeiscm.csp.service.csplog;
  2.  
  3. import com.juepeiscm.admin.api.domain.SysOperLog;
  4. import com.juepeiscm.csp.domain.csplog.SysOperCspLog;
  5.  
  6. import java.util.List;
  7.  
  8. /**
  9. * @Author: py.sun
  10. * @Date: 2022/9/7 15:02
  11. */
  12. public interface ISysOperCspLogService {
  13. void insertOperlog(SysOperCspLog var1);
  14.  
  15. List<SysOperCspLog> selectOperLogList(SysOperCspLog var1);
  16.  
  17. List<String> selectOperLogListTitle();
  18.  
  19. int deleteOperLogByIds(Long[] var1);
  20.  
  21. SysOperLog selectOperLogById(Long var1);
  22.  
  23. void cleanOperLog();
  24. }

5.Service实现

  1. package com.juepeiscm.csp.service.impl.csplog;
  2.  
  3. import com.juepeiscm.admin.api.domain.SysOperLog;
  4. import com.juepeiscm.common.core.domain.AjaxResult;
  5. import com.juepeiscm.common.core.domain.entity.SysDept;
  6. import com.juepeiscm.common.core.domain.entity.SysUser;
  7. import com.juepeiscm.common.core.domain.model.LoginUser;
  8. import com.juepeiscm.common.exception.CustomException;
  9. import com.juepeiscm.common.utils.SecurityUtils;
  10. import com.juepeiscm.common.utils.ServletUtils;
  11. import com.juepeiscm.common.utils.StringUtils;
  12. import com.juepeiscm.csp.domain.csplog.SysOperCspLog;
  13. import com.juepeiscm.csp.mapper.csplog.SysOperCspLogMapper;
  14. import com.juepeiscm.csp.service.csplog.ISysOperCspLogService;
  15. import com.juepeiscm.framework.web.service.TokenService;
  16. import com.juepeiscm.uam.service.ISysDeptService;
  17. import com.juepeiscm.uam.version.UamVersion;
  18. import org.apache.dubbo.config.annotation.Reference;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.stereotype.Service;
  21.  
  22. import java.util.List;
  23.  
  24. /**
  25. * @Author: py.sun
  26. * @Date: 2022/9/7 15:03
  27. */
  28. @Service
  29. public class SysOperCspLogServiceImpl implements ISysOperCspLogService {
  30. @Autowired
  31. private SysOperCspLogMapper operLogMapper;
  32.  
  33. @Autowired
  34. private TokenService tokenService;
  35.  
  36. @Reference(version = UamVersion.idV)
  37. public ISysDeptService deptService;
  38.  
  39. @Override
  40. public void insertOperlog(SysOperCspLog sysOperCspLog) {
  41. try {
  42. this.operLogMapper.insertOperlog(sysOperCspLog);
  43. } catch (Exception e) {
  44. e.printStackTrace();
  45. throw new CustomException("CSP系统日志插入失败,请联系管理员!!!");
  46. }
  47.  
  48. }
  49.  
  50. @Override
  51. public List<SysOperCspLog> selectOperLogList(SysOperCspLog sysOperCspLog) {
  52. return this.operLogMapper.selectOperLogList(sysOperCspLog);
  53. }
  54.  
  55. @Override
  56. public List<String> selectOperLogListTitle() {
  57. return this.operLogMapper.selectOperLogListTitle();
  58. }
  59.  
  60. @Override
  61. public int deleteOperLogByIds(Long[] operIds) {
  62. return this.operLogMapper.deleteOperLogByIds(operIds);
  63. }
  64.  
  65. @Override
  66. public SysOperLog selectOperLogById(Long operId) {
  67. return this.operLogMapper.selectOperLogById(operId);
  68. }
  69.  
  70. @Override
  71. public void cleanOperLog() {
  72. this.operLogMapper.cleanOperLog();
  73. }
  74. }

6.Mapper接口

  1. package com.juepeiscm.csp.mapper.csplog;
  2.  
  3. import com.juepeiscm.admin.api.domain.SysOperLog;
  4. import com.juepeiscm.csp.domain.csplog.SysOperCspLog;
  5.  
  6. import java.util.List;
  7.  
  8. /**
  9. * @Author: py.sun
  10. * @Date: 2022/9/7 15:06
  11. */
  12. public interface SysOperCspLogMapper {
  13.  
  14. void insertOperlog(SysOperCspLog var1);
  15.  
  16. List<SysOperCspLog> selectOperLogList(SysOperCspLog sysOperCspLog);
  17.  
  18. List<String> selectOperLogListTitle();
  19.  
  20. int deleteOperLogByIds(Long[] var1);
  21.  
  22. SysOperLog selectOperLogById(Long var1);
  23.  
  24. void cleanOperLog();
  25. }

7.Mapper.xml(我用的是Mybatis)

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.juepeiscm.csp.mapper.csplog.SysOperCspLogMapper">
  6.  
  7. <resultMap type="SysOperCspLog" id="SysOperLogResult">
  8. <id property="operId" column="oper_id" />
  9. <result property="title" column="title" />
  10. <result property="businessType" column="business_type" />
  11. <result property="method" column="method" />
  12. <result property="requestMethod" column="request_method" />
  13. <result property="operatorType" column="operator_type" />
  14. <result property="operName" column="oper_name" />
  15. <result property="deptName" column="dept_name" />
  16. <result property="operUrl" column="oper_url" />
  17. <result property="operIp" column="oper_ip" />
  18. <result property="operLocation" column="oper_location" />
  19. <result property="operParam" column="oper_param" />
  20. <result property="jsonResult" column="json_result" />
  21. <result property="status" column="status" />
  22. <result property="errorMsg" column="error_msg" />
  23. <result property="operTime" column="oper_time" />
  24. </resultMap>
  25.  
  26. <sql id="selectOperLogVo">
  27. select oper_id, title, business_type, method, request_method, operator_type, oper_name, dept_name, oper_url, oper_ip, oper_location, oper_param, json_result, status, error_msg, oper_time
  28. from sys_oper_csp_log
  29. </sql>
  30.  
  31. <insert id="insertOperlog" parameterType="SysOperCspLog">
  32. insert into sys_oper_csp_log(title, business_type, method, request_method, operator_type, oper_name, dept_name, oper_url, oper_ip, oper_location, oper_param, json_result, status, error_msg, oper_time)
  33. values (#{title}, #{businessType}, #{method}, #{requestMethod}, #{operatorType}, #{operName}, #{deptName}, #{operUrl}, #{operIp}, #{operLocation}, #{operParam}, #{jsonResult}, #{status}, #{errorMsg}, sysdate())
  34. </insert>
  35.  
  36. <select id="selectOperLogList" parameterType="SysOperCspLog" resultMap="SysOperLogResult">
  37. <include refid="selectOperLogVo"/>
  38. <where>
  39. <if test="title != null and title != ''">
  40. AND title like concat('%', #{title}, '%')
  41. </if>
  42. <if test="businessType != null and businessType != ''">
  43. AND business_type = #{businessType}
  44. </if>
  45. <if test="businessTypes != null and businessTypes.length > 0">
  46. AND business_type in
  47. <foreach collection="businessTypes" item="businessType" open="(" separator="," close=")">
  48. #{businessType}
  49. </foreach>
  50. </if>
  51. <if test="status != null">
  52. AND status = #{status}
  53. </if>
  54. <if test="operName != null and operName != ''">
  55. AND oper_name like concat('%', #{operName}, '%')
  56. </if>
  57. <if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
  58. and date_format(oper_time,'%y%m%d') &gt;= date_format(#{params.beginTime},'%y%m%d')
  59. </if>
  60. <if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
  61. and date_format(oper_time,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
  62. </if>
  63. </where>
  64. order by oper_id desc
  65. </select>
  66.  
  67. <delete id="deleteOperLogByIds" parameterType="Long">
  68. delete from sys_oper_csp_log where oper_id in
  69. <foreach collection="array" item="operId" open="(" separator="," close=")">
  70. #{operId}
  71. </foreach>
  72. </delete>
  73.  
  74. <select id="selectOperLogById" parameterType="Long" resultMap="SysOperLogResult">
  75. <include refid="selectOperLogVo"/>
  76. where oper_id = #{operId}
  77. </select>
  78.  
  79. <select id="selectOperLogListTitle" resultType="java.lang.String">
  80. select distinct(title) from sys_oper_csp_log
  81. </select>
  82.  
  83. <update id="cleanOperLog">
  84. truncate table sys_oper_csp_log
  85. </update>
  86.  
  87. </mapper>

8.CspLog

定义一个日志管理的名称:CspLog

  1. package com.juepeiscm.csp.annotation;
  2.  
  3. import com.juepeiscm.common.enums.BusinessType;
  4. import com.juepeiscm.common.enums.OperatorType;
  5.  
  6. import java.lang.annotation.*;
  7.  
  8. /**
  9. * CSP系统的日志管理
  10. * @Author: py.sun
  11. * @Date: 2022/9/7 14:42
  12. * @Target表示注解可以使用到哪些地方,可以是类,方法,或者是属性上,定义在ElementType枚举中:
  13. * @Retention作用是定义被它所注解的注解保留多久,一共有三种策略,定义在RetentionPolicy枚举中:
  14. *
  15. * 我们的@CspLog注解,可以作用在方法和参数上,将由编译器记录在类文件中,并在运行时由VM保留,因此可以反射性地读取。该注解是通过AOP进行解析的
  16. */
  17. @Target({ElementType.PARAMETER, ElementType.METHOD})
  18. @Retention(RetentionPolicy.RUNTIME)
  19. @Documented
  20. public @interface CspLog {
  21. /**
  22. * 模块
  23. * @return
  24. */
  25. String title() default "";
  26.  
  27. /**
  28. * 功能
  29. * @return
  30. */
  31. BusinessType businessType() default BusinessType.OTHER;
  32.  
  33. /**
  34. * 操作人类别
  35. * @return
  36. */
  37. OperatorType operatorType() default OperatorType.MANAGE;
  38.  
  39. /**
  40. * 是否保存请求的参数
  41. * @return
  42. */
  43. boolean isSaveRequestData() default true;
  44. }

9.实体类SysOperCspLog

  1. package com.juepeiscm.csp.domain.csplog;
  2.  
  3. import com.fasterxml.jackson.annotation.JsonFormat;
  4. import com.juepeiscm.common.annotation.Excel;
  5. import com.juepeiscm.common.core.domain.BaseEntity;
  6.  
  7. import java.util.Date;
  8.  
  9. /**
  10. * @Author: py.sun
  11. * @Date: 2022/9/7 15:04
  12. */
  13. public class SysOperCspLog extends BaseEntity {
  14. private static final long serialVersionUID = 1L;
  15. @Excel(
  16. name = "操作序号",
  17. cellType = Excel.ColumnType.NUMERIC
  18. )
  19. private Long operId;
  20. @Excel(
  21. name = "操作模块"
  22. )
  23. private String title;
  24. @Excel(
  25. name = "业务类型",
  26. readConverterExp = "0=其它,1=新增,2=修改,3=删除,4=授权,5=导出,6=导入,7=强退,8=生成代码,9=清空数据"
  27. )
  28. private Integer businessType;
  29. private Integer[] businessTypes;
  30. @Excel(
  31. name = "请求方法"
  32. )
  33. private String method;
  34. @Excel(
  35. name = "请求方式"
  36. )
  37. private String requestMethod;
  38. @Excel(
  39. name = "操作类别",
  40. readConverterExp = "0=其它,1=后台用户,2=手机端用户"
  41. )
  42. private Integer operatorType;
  43. @Excel(
  44. name = "操作人员"
  45. )
  46. private String operName;
  47. @Excel(
  48. name = "部门名称"
  49. )
  50. private String deptName;
  51. @Excel(
  52. name = "请求地址"
  53. )
  54. private String operUrl;
  55. @Excel(
  56. name = "操作地址"
  57. )
  58. private String operIp;
  59. @Excel(
  60. name = "操作地点"
  61. )
  62. private String operLocation;
  63. @Excel(
  64. name = "请求参数"
  65. )
  66. private String operParam;
  67. @Excel(
  68. name = "返回参数"
  69. )
  70. private String jsonResult;
  71. @Excel(
  72. name = "状态",
  73. readConverterExp = "0=正常,1=异常"
  74. )
  75. private Integer status;
  76. @Excel(
  77. name = "错误消息"
  78. )
  79. private String errorMsg;
  80. @JsonFormat(
  81. pattern = "yyyy-MM-dd HH:mm:ss"
  82. )
  83. @Excel(
  84. name = "操作时间",
  85. width = 30.0D,
  86. dateFormat = "yyyy-MM-dd HH:mm:ss"
  87. )
  88. private Date operTime;
  89.  
  90. public SysOperCspLog() {
  91. }
  92.  
  93. public Long getOperId() {
  94. return this.operId;
  95. }
  96.  
  97. public void setOperId(Long operId) {
  98. this.operId = operId;
  99. }
  100.  
  101. public String getTitle() {
  102. return this.title;
  103. }
  104.  
  105. public void setTitle(String title) {
  106. this.title = title;
  107. }
  108.  
  109. public Integer getBusinessType() {
  110. return this.businessType;
  111. }
  112.  
  113. public void setBusinessType(Integer businessType) {
  114. this.businessType = businessType;
  115. }
  116.  
  117. public Integer[] getBusinessTypes() {
  118. return this.businessTypes;
  119. }
  120.  
  121. public void setBusinessTypes(Integer[] businessTypes) {
  122. this.businessTypes = businessTypes;
  123. }
  124.  
  125. public String getMethod() {
  126. return this.method;
  127. }
  128.  
  129. public void setMethod(String method) {
  130. this.method = method;
  131. }
  132.  
  133. public String getRequestMethod() {
  134. return this.requestMethod;
  135. }
  136.  
  137. public void setRequestMethod(String requestMethod) {
  138. this.requestMethod = requestMethod;
  139. }
  140.  
  141. public Integer getOperatorType() {
  142. return this.operatorType;
  143. }
  144.  
  145. public void setOperatorType(Integer operatorType) {
  146. this.operatorType = operatorType;
  147. }
  148.  
  149. public String getOperName() {
  150. return this.operName;
  151. }
  152.  
  153. public void setOperName(String operName) {
  154. this.operName = operName;
  155. }
  156.  
  157. public String getDeptName() {
  158. return this.deptName;
  159. }
  160.  
  161. public void setDeptName(String deptName) {
  162. this.deptName = deptName;
  163. }
  164.  
  165. public String getOperUrl() {
  166. return this.operUrl;
  167. }
  168.  
  169. public void setOperUrl(String operUrl) {
  170. this.operUrl = operUrl;
  171. }
  172.  
  173. public String getOperIp() {
  174. return this.operIp;
  175. }
  176.  
  177. public void setOperIp(String operIp) {
  178. this.operIp = operIp;
  179. }
  180.  
  181. public String getOperLocation() {
  182. return this.operLocation;
  183. }
  184.  
  185. public void setOperLocation(String operLocation) {
  186. this.operLocation = operLocation;
  187. }
  188.  
  189. public String getOperParam() {
  190. return this.operParam;
  191. }
  192.  
  193. public void setOperParam(String operParam) {
  194. this.operParam = operParam;
  195. }
  196.  
  197. public String getJsonResult() {
  198. return this.jsonResult;
  199. }
  200.  
  201. public void setJsonResult(String jsonResult) {
  202. this.jsonResult = jsonResult;
  203. }
  204.  
  205. public Integer getStatus() {
  206. return this.status;
  207. }
  208.  
  209. public void setStatus(Integer status) {
  210. this.status = status;
  211. }
  212.  
  213. public String getErrorMsg() {
  214. return this.errorMsg;
  215. }
  216.  
  217. public void setErrorMsg(String errorMsg) {
  218. this.errorMsg = errorMsg;
  219. }
  220.  
  221. public Date getOperTime() {
  222. return this.operTime;
  223. }
  224.  
  225. public void setOperTime(Date operTime) {
  226. this.operTime = operTime;
  227. }
  228. }

10. 定义日志管理的切面

大家一定要记住哈,所有针对实体的SysOperCspLog赋值操作必须在这里main执行。

  1. package com.juepeiscm.csp.controller.utils;
  2.  
  3. import com.alibaba.fastjson.JSON;
  4. import com.juepeiscm.common.core.domain.entity.SysDept;
  5. import com.juepeiscm.common.core.domain.model.LoginUser;
  6. import com.juepeiscm.common.enums.BusinessStatus;
  7. import com.juepeiscm.common.enums.HttpMethod;
  8. import com.juepeiscm.common.utils.ServletUtils;
  9. import com.juepeiscm.common.utils.StringUtils;
  10. import com.juepeiscm.common.utils.ip.IpUtils;
  11. import com.juepeiscm.common.utils.spring.SpringUtils;
  12. import com.juepeiscm.csp.annotation.CspLog;
  13. import com.juepeiscm.csp.domain.csplog.SysOperCspLog;
  14. import com.juepeiscm.framework.aspectj.LogAspect;
  15. import com.juepeiscm.framework.manager.AsyncManager;
  16. import com.juepeiscm.framework.web.service.TokenService;
  17. import com.juepeiscm.uam.service.ISysDeptService;
  18. import com.juepeiscm.uam.version.UamVersion;
  19. import org.apache.dubbo.config.annotation.Reference;
  20. import org.aspectj.lang.JoinPoint;
  21. import org.aspectj.lang.Signature;
  22. import org.aspectj.lang.annotation.AfterReturning;
  23. import org.aspectj.lang.annotation.AfterThrowing;
  24. import org.aspectj.lang.annotation.Aspect;
  25. import org.aspectj.lang.annotation.Pointcut;
  26. import org.aspectj.lang.reflect.MethodSignature;
  27. import org.slf4j.Logger;
  28. import org.slf4j.LoggerFactory;
  29. import org.springframework.stereotype.Component;
  30. import org.springframework.validation.BindingResult;
  31. import org.springframework.web.multipart.MultipartFile;
  32. import org.springframework.web.servlet.HandlerMapping;
  33.  
  34. import javax.servlet.http.HttpServletRequest;
  35. import javax.servlet.http.HttpServletResponse;
  36. import java.lang.reflect.Method;
  37. import java.util.Collection;
  38. import java.util.Iterator;
  39. import java.util.Map;
  40.  
  41. /**
  42. * @Author: py.sun
  43. * @Date: 2022/9/7 16:31
  44. * 操作日志记录处理
  45. */
  46. @Aspect
  47. @Component
  48. public class CspLogAspect {
  49. private static final Logger log = LoggerFactory.getLogger(CspLog.class);
  50.  
  51. @Reference(version = UamVersion.idV)
  52. public ISysDeptService deptService;
  53.  
  54. public CspLogAspect() {
  55. }
  56.  
  57. //把@CspLog配置为切入点。 配置织入点
  58. @Pointcut("@annotation(com.juepeiscm.csp.annotation.CspLog)")
  59. public void logPointCut() {
  60. }
  61.  
  62. //拦截异常操作
  63. // 处理完请求后执行该方法。也就是用@CspLog注解的方法,执行完后,调用handleLog方法,处理返回结果。
  64. @AfterReturning(
  65. pointcut = "logPointCut()",
  66. returning = "jsonResult"
  67. )
  68. public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
  69. this.handleLog(joinPoint, (Exception)null, jsonResult);
  70. }
  71.  
  72. @AfterThrowing(
  73. value = "logPointCut()",
  74. throwing = "e"
  75. )
  76. public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
  77. this.handleLog(joinPoint, e, (Object)null);
  78. }
  79.  
  80. // 如果函数抛出了异常,也是执行handleLog方法,不过和正常返回的参数不一样,此处是为了处理异常。
  81. protected void handleLog(JoinPoint joinPoint, Exception e, Object jsonResult) {
  82. try {
  83. // 获得注解
  84. CspLog controllerLog = this.getAnnotationLog(joinPoint);
  85. if (controllerLog == null) {
  86. return;
  87. }
  88.  
  89. // 获取当前的用户
  90. LoginUser loginUser = ((TokenService) SpringUtils.getBean(TokenService.class)).getLoginUser(ServletUtils.getRequest());
  91. // *========数据库日志=========*//
  92. SysOperCspLog operLog = new SysOperCspLog();
  93. operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
  94. // 请求的地址
  95. String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
  96. operLog.setOperIp(ip);
  97. // 返回参数
  98. operLog.setJsonResult(JSON.toJSONString(jsonResult));
  99. operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
  100. if (loginUser != null) {
  101. operLog.setOperName(loginUser.getUsername());
  102. }
  103.  
  104. // 获取当前登录用户的部门名称
  105. SysDept sysDept = deptService.selectDeptIdByUserIdAndAppId(loginUser.getUser().getUserId(), "oms");
  106. if(sysDept != null && StringUtils.isNotEmpty(sysDept.getDeptName())){
  107. operLog.setDeptName(sysDept.getDeptName());
  108. }
  109.  
  110. if (e != null) {
  111. operLog.setStatus(BusinessStatus.FAIL.ordinal());
  112. operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
  113. }
  114.  
  115. // 设置方法名称
  116. String className = joinPoint.getTarget().getClass().getName();
  117. String methodName = joinPoint.getSignature().getName();
  118. operLog.setMethod(className + "." + methodName + "()");
  119. // 设置请求方式
  120. operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
  121. // 处理设置注解上的参数
  122. this.getControllerMethodDescription(joinPoint, controllerLog, operLog);
  123. // 保存数据库
  124. AsyncManager.me().execute(AsyncFactoryCsp.recordOper(operLog));
  125. } catch (Exception var10) {
  126. // 记录本地异常日志
  127. log.error("==前置通知异常==");
  128. log.error("异常信息:{}", var10.getMessage());
  129. var10.printStackTrace();
  130. }
  131.  
  132. }
  133.  
  134. public void getControllerMethodDescription(JoinPoint joinPoint, CspLog log, SysOperCspLog operLog) throws Exception {
  135. operLog.setBusinessType(log.businessType().ordinal());
  136. operLog.setTitle(log.title());
  137. operLog.setOperatorType(log.operatorType().ordinal());
  138. if (log.isSaveRequestData()) {
  139. this.setRequestValue(joinPoint, operLog);
  140. }
  141.  
  142. }
  143.  
  144. private void setRequestValue(JoinPoint joinPoint, SysOperCspLog operLog) throws Exception {
  145. String requestMethod = operLog.getRequestMethod();
  146. if (!HttpMethod.PUT.name().equals(requestMethod) && !HttpMethod.POST.name().equals(requestMethod)) {
  147. Map<?, ?> paramsMap = (Map)ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
  148. operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
  149. } else {
  150. String params = this.argsArrayToString(joinPoint.getArgs());
  151. operLog.setOperParam(StringUtils.substring(params, 0, 2000));
  152. }
  153.  
  154. }
  155.  
  156. private CspLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
  157. Signature signature = joinPoint.getSignature();
  158. MethodSignature methodSignature = (MethodSignature)signature;
  159. Method method = methodSignature.getMethod();
  160. return method != null ? (CspLog)method.getAnnotation(CspLog.class) : null;
  161. }
  162.  
  163. private String argsArrayToString(Object[] paramsArray) {
  164. String params = "";
  165. if (paramsArray != null && paramsArray.length > 0) {
  166. for(int i = 0; i < paramsArray.length; ++i) {
  167. if (StringUtils.isNotNull(paramsArray[i]) && !this.isFilterObject(paramsArray[i])) {
  168. Object jsonObj = JSON.toJSON(paramsArray[i]);
  169. params = params + jsonObj.toString() + " ";
  170. }
  171. }
  172. }
  173.  
  174. return params.trim();
  175. }
  176.  
  177. public boolean isFilterObject(Object o) {
  178. Class<?> clazz = o.getClass();
  179. if (clazz.isArray()) {
  180. return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
  181. } else {
  182. Iterator iter;
  183. if (Collection.class.isAssignableFrom(clazz)) {
  184. Collection collection = (Collection)o;
  185. iter = collection.iterator();
  186. if (iter.hasNext()) {
  187. return iter.next() instanceof MultipartFile;
  188. }
  189. } else if (Map.class.isAssignableFrom(clazz)) {
  190. Map map = (Map)o;
  191. iter = map.entrySet().iterator();
  192. if (iter.hasNext()) {
  193. Map.Entry entry = (Map.Entry)iter.next();
  194. return entry.getValue() instanceof MultipartFile;
  195. }
  196. }
  197.  
  198. return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse || o instanceof BindingResult;
  199. }
  200. }
  201. }

11.AsyncFactoryCsp

  1. package com.juepeiscm.csp.controller.utils;
  2. import com.juepeiscm.common.utils.ip.AddressUtils;
  3. import com.juepeiscm.common.utils.spring.SpringUtils;
  4. import com.juepeiscm.csp.domain.csplog.SysOperCspLog;
  5. import com.juepeiscm.csp.service.csplog.ISysOperCspLogService;
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8.  
  9. import java.util.TimerTask;
  10.  
  11. /**
  12. * @Author: py.sun
  13. * @Date: 2022/9/7 16:47
  14. */
  15. public class AsyncFactoryCsp {
  16. private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");
  17.  
  18. public AsyncFactoryCsp() {
  19. }
  20.  
  21. public static TimerTask recordOper(final SysOperCspLog operLog) {
  22. return new TimerTask() {
  23. public void run() {
  24. operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
  25. ((ISysOperCspLogService) SpringUtils.getBean(ISysOperCspLogService.class)).insertOperlog(operLog);
  26. }
  27. };
  28. }
  29. }

12. 写一个Controller的Demo来执行一条日志试试

在这里插入代码片package com.juepeiscm.csp.controller.order;

  1. 在这里插入代码片package com.juepeiscm.csp.controller.order;
  2.  
  3. import com.alibaba.fastjson.JSON;
  4. import com.juepeiscm.admin.api.service.ISysDictDataService;
  5. import com.juepeiscm.common.annotation.RepeatSubmit;
  6. import com.juepeiscm.common.core.controller.BaseController;
  7. import com.juepeiscm.common.core.domain.AjaxResult;
  8. import com.juepeiscm.common.core.domain.entity.SysDictData;
  9. import com.juepeiscm.common.core.page.TableDataInfo;
  10. import com.juepeiscm.common.enums.BusinessType;
  11. import com.juepeiscm.common.exception.BaseException;
  12. import com.juepeiscm.common.utils.StringUtils;
  13. import com.juepeiscm.common.utils.poi.ExcelUtil;
  14. import com.juepeiscm.csp.annotation.CspLog;
  15. import com.juepeiscm.csp.domain.order.CspGodownEntry;
  16. import com.juepeiscm.csp.domain.order.CspGodownEntryDetails;
  17. import com.juepeiscm.csp.service.common.MenuLogService;
  18. import com.juepeiscm.csp.service.data.ICspGoodsdataService;
  19. import com.juepeiscm.csp.service.order.ICspGodownEntryService;
  20. import com.juepeiscm.csp.vo.GodownEntryExcel;
  21. import com.juepeiscm.csp.vo.GoodsDataForGodownEntryDetails;
  22. import io.swagger.annotations.Api;
  23. import io.swagger.annotations.ApiOperation;
  24. import org.slf4j.Logger;
  25. import org.slf4j.LoggerFactory;
  26. import org.springframework.beans.factory.annotation.Autowired;
  27. import org.springframework.security.access.prepost.PreAuthorize;
  28. import org.springframework.util.CollectionUtils;
  29. import org.springframework.web.bind.annotation.*;
  30. import org.springframework.web.multipart.MultipartFile;
  31.  
  32. import javax.validation.Valid;
  33. import java.math.BigDecimal;
  34. import java.math.RoundingMode;
  35. import java.util.*;
  36. import java.util.stream.Collectors;
  37.  
  38. /**
  39. * 入库订单Controller
  40. *
  41. * @author juepeiscm
  42. * @date 2021-07-23
  43. */
  44. @Api(tags = "入库订单接口")
  45. @RestController
  46. @RequestMapping("/order/godownEntry")
  47. public class CspGodownEntryController extends BaseController {
  48.  
  49. private static final Logger logger = LoggerFactory.getLogger(CspGodownEntryController.class);
  50.  
  51. @Autowired
  52. private ICspGodownEntryService cspGodownEntryService;
  53. @Autowired
  54. private ICspGoodsdataService goodsDataService;
  55. @Autowired
  56. private MenuLogService menuLogService;
  57. @Autowired
  58. private ISysDictDataService sysDictDataService;
  59.  
  60. /**
  61. * 新增入库订单Demo
  62. */
  63. @PreAuthorize("@ss.hasPermi('order:godownEntry:add')")
  64. @ApiOperation(value = "新增入库订单")
  65. @CspLog(title = "入库订单demo4", businessType = BusinessType.INSERT)
  66. @PostMapping("/addOrder")
  67. @RepeatSubmit
  68. public AjaxResult addDemo(@RequestBody @Valid CspGodownEntry godownEntry) {
  69. try {
  70. return toAjax(cspGodownEntryService.insertOmsGodownEntry(godownEntry));
  71. } catch (Exception e) {
  72. e.printStackTrace();
  73. return AjaxResult.error("新增失败,请联系管理员");
  74. }
  75. }
  76. }

测试下,看看数据库内容

到此这篇关于SpringBoot利用AOP实现一个日志管理详解的文章就介绍到这了,更多相关SpringBoot AOP日志管理内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号