作者 朱兆平

日志处理

  1 +package com.tianbo.warehouse.annotation;
  2 +
  3 +
  4 +import java.lang.annotation.*;
  5 +
  6 +@Retention(RetentionPolicy.RUNTIME)
  7 +@Target({ElementType.METHOD})
  8 +@Documented
  9 +/**
  10 + * 自定义日志注解
  11 + */
  12 +public @interface LogAnnotation {
  13 +
  14 + /**模块名称*/
  15 + String moduleName() default "";
  16 +
  17 + /**操作内容*/
  18 + String operate() default "";
  19 +}
  1 +package com.tianbo.warehouse.annotation;
  2 +
  3 +import com.alibaba.fastjson.JSON;
  4 +import com.tianbo.warehouse.model.LOGWithBLOBs;
  5 +import com.tianbo.warehouse.service.LogService;
  6 +import com.tianbo.warehouse.util.IO.StreamUtil;
  7 +import org.aspectj.lang.JoinPoint;
  8 +import org.aspectj.lang.ProceedingJoinPoint;
  9 +import org.aspectj.lang.annotation.*;
  10 +import org.aspectj.lang.reflect.MethodSignature;
  11 +import org.springframework.beans.factory.annotation.Autowired;
  12 +import org.springframework.security.core.context.SecurityContextHolder;
  13 +import org.springframework.security.core.userdetails.UserDetails;
  14 +import org.springframework.stereotype.Component;
  15 +import org.springframework.validation.BindingResult;
  16 +import org.springframework.web.context.request.RequestContextHolder;
  17 +import org.springframework.web.context.request.ServletRequestAttributes;
  18 +
  19 +import javax.servlet.http.HttpServletRequest;
  20 +import javax.servlet.http.HttpServletResponse;
  21 +import java.lang.reflect.Method;
  22 +import java.util.List;
  23 +import java.util.stream.Collectors;
  24 +import java.util.stream.Stream;
  25 +
  26 +
  27 +@Aspect
  28 +@Component
  29 +public class LogAnnotationAOP {
  30 +
  31 + @Autowired
  32 + private LogService logService;
  33 +
  34 + private LOGWithBLOBs log;
  35 +
  36 + @Pointcut("@annotation(com.tianbo.warehouse.annotation.LogAnnotation)")
  37 + public void annotationPointCut(){
  38 +
  39 + }
  40 +
  41 + @Before("annotationPointCut()")
  42 + public void before(JoinPoint point){
  43 + //获取当前登录用户信息
  44 + try{
  45 + UserDetails userDetails =(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  46 + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  47 + HttpServletRequest request = attributes.getRequest();
  48 + String requestRemoteAddr = request.getRemoteAddr();
  49 +
  50 + log.setIp(requestRemoteAddr);
  51 + log.setUsername(userDetails.getUsername());
  52 + }catch (Exception e){
  53 + e.printStackTrace();
  54 + }
  55 +
  56 + try{
  57 + String targetName = point.getTarget().getClass().getName();
  58 + Class targetClass = Class.forName(targetName);
  59 +
  60 + MethodSignature signature = (MethodSignature) point.getSignature();
  61 + Method method= signature.getMethod();
  62 + LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
  63 + System.out.print("打印:"+annotation.moduleName()+" 开始前");
  64 + String methodName = point.getSignature().getName();
  65 +// Method[] methods = targetClass.getMethods();
  66 +
  67 +
  68 + if(annotation != null){
  69 + log.setModelnamecn(annotation.moduleName());
  70 + log.setOperatenamecn(annotation.operate());
  71 + }
  72 + log.setClassname(targetName);
  73 + log.setMethodname(methodName);
  74 +
  75 + // 获得参数列表
  76 + Object[] params = point.getArgs();
  77 + if(params.length>0){
  78 + //序列化时过滤掉request和response,参考资料为:https://blog.csdn.net/hbn1326317071/article/details/83818059
  79 + List<Object> logArgs = StreamUtil.streamOf(params)
  80 + .filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse) && !(arg instanceof BindingResult)))
  81 + .collect(Collectors.toList());
  82 +
  83 + //将参数列表转成JSON存储
  84 + log.setParameters(JSON.toJSONString(logArgs));
  85 + }
  86 +
  87 + }catch (ClassNotFoundException e){
  88 + e.printStackTrace();
  89 + }
  90 +
  91 +
  92 +
  93 +
  94 + }
  95 +
  96 + @Around("annotationPointCut()")
  97 + public Object advice(ProceedingJoinPoint joinPoint){
  98 + System.out.println("通知之开始");
  99 + log = new LOGWithBLOBs();
  100 +
  101 + Object retmsg=null;
  102 + try {
  103 + retmsg=joinPoint.proceed();
  104 + System.err.println("++++++++"+retmsg);
  105 + } catch (Throwable e) {
  106 + e.printStackTrace();
  107 + }
  108 + System.out.println("通知之结束");
  109 + return retmsg;
  110 + }
  111 +
  112 + @After("annotationPointCut()")
  113 + public void after(){
  114 + System.out.println("after方法执行后");
  115 + }
  116 +
  117 + /**
  118 + * 方法正常完成后执行方法
  119 + * @param retmsg 这里的retmsg= advice中的Object retmsg
  120 + */
  121 + @AfterReturning(returning = "retmsg",pointcut="annotationPointCut()")
  122 + public void afterReturn(Object retmsg) throws Throwable{
  123 +
  124 + // 处理完请求,返回内容
  125 + log.setResult(JSON.toJSONString(retmsg));
  126 +
  127 + logService.insertSelective(log);
  128 + }
  129 +}
1 package com.tianbo.warehouse.controller; 1 package com.tianbo.warehouse.controller;
2 2
3 import com.github.pagehelper.PageInfo; 3 import com.github.pagehelper.PageInfo;
  4 +import com.tianbo.warehouse.annotation.LogAnnotation;
4 import com.tianbo.warehouse.annotation.UserPasswordMd5; 5 import com.tianbo.warehouse.annotation.UserPasswordMd5;
5 import com.tianbo.warehouse.controller.response.ResultJson; 6 import com.tianbo.warehouse.controller.response.ResultJson;
6 import com.tianbo.warehouse.model.USERS; 7 import com.tianbo.warehouse.model.USERS;
@@ -50,6 +51,7 @@ public class UserController { @@ -50,6 +51,7 @@ public class UserController {
50 } 51 }
51 52
52 @UserPasswordMd5 53 @UserPasswordMd5
  54 + @LogAnnotation(moduleName = "用户管理",operate = "用户添加")
53 @PostMapping("/user/add") 55 @PostMapping("/user/add")
54 public ResultJson addUser(@RequestBody @Valid USERS user, HttpServletRequest request, HttpServletResponse response, BindingResult bindingResult){ 56 public ResultJson addUser(@RequestBody @Valid USERS user, HttpServletRequest request, HttpServletResponse response, BindingResult bindingResult){
55 57
  1 +package com.tianbo.warehouse.dao;
  2 +
  3 +import com.tianbo.warehouse.model.LOG;
  4 +import com.tianbo.warehouse.model.LOGWithBLOBs;
  5 +
  6 +public interface LOGMapper {
  7 + int deleteByPrimaryKey(Integer logid);
  8 +
  9 + int insert(LOGWithBLOBs record);
  10 +
  11 + int insertSelective(LOGWithBLOBs record);
  12 +
  13 + LOGWithBLOBs selectByPrimaryKey(Integer logid);
  14 +
  15 + int updateByPrimaryKeySelective(LOGWithBLOBs record);
  16 +
  17 + int updateByPrimaryKeyWithBLOBs(LOGWithBLOBs record);
  18 +
  19 + int updateByPrimaryKey(LOG record);
  20 +}
  1 +package com.tianbo.warehouse.model;
  2 +
  3 +import java.util.Date;
  4 +
  5 +public class LOG {
  6 + private Integer logid;
  7 +
  8 + private String username;
  9 +
  10 + private String ip;
  11 +
  12 + private Date logcreattime;
  13 +
  14 + private String methodname;
  15 +
  16 + private String modelnamecn;
  17 +
  18 + private String operatenamecn;
  19 +
  20 + private String classname;
  21 +
  22 + public Integer getLogid() {
  23 + return logid;
  24 + }
  25 +
  26 + public void setLogid(Integer logid) {
  27 + this.logid = logid;
  28 + }
  29 +
  30 + public String getUsername() {
  31 + return username;
  32 + }
  33 +
  34 + public void setUsername(String username) {
  35 + this.username = username == null ? null : username.trim();
  36 + }
  37 +
  38 + public String getIp() {
  39 + return ip;
  40 + }
  41 +
  42 + public void setIp(String ip) {
  43 + this.ip = ip == null ? null : ip.trim();
  44 + }
  45 +
  46 + public Date getLogcreattime() {
  47 + return logcreattime;
  48 + }
  49 +
  50 + public void setLogcreattime(Date logcreattime) {
  51 + this.logcreattime = logcreattime;
  52 + }
  53 +
  54 + public String getMethodname() {
  55 + return methodname;
  56 + }
  57 +
  58 + public void setMethodname(String methodname) {
  59 + this.methodname = methodname == null ? null : methodname.trim();
  60 + }
  61 +
  62 + public String getModelnamecn() {
  63 + return modelnamecn;
  64 + }
  65 +
  66 + public void setModelnamecn(String modelnamecn) {
  67 + this.modelnamecn = modelnamecn == null ? null : modelnamecn.trim();
  68 + }
  69 +
  70 + public String getOperatenamecn() {
  71 + return operatenamecn;
  72 + }
  73 +
  74 + public void setOperatenamecn(String operatenamecn) {
  75 + this.operatenamecn = operatenamecn == null ? null : operatenamecn.trim();
  76 + }
  77 +
  78 + public String getClassname() {
  79 + return classname;
  80 + }
  81 +
  82 + public void setClassname(String classname) {
  83 + this.classname = classname == null ? null : classname.trim();
  84 + }
  85 +}
  1 +package com.tianbo.warehouse.model;
  2 +
  3 +public class LOGWithBLOBs extends LOG {
  4 + private String parameters;
  5 +
  6 + private String result;
  7 +
  8 + public String getParameters() {
  9 + return parameters;
  10 + }
  11 +
  12 + public void setParameters(String parameters) {
  13 + this.parameters = parameters == null ? null : parameters.trim();
  14 + }
  15 +
  16 + public String getResult() {
  17 + return result;
  18 + }
  19 +
  20 + public void setResult(String result) {
  21 + this.result = result == null ? null : result.trim();
  22 + }
  23 +}
1 package com.tianbo.warehouse.model; 1 package com.tianbo.warehouse.model;
2 2
  3 +import com.alibaba.fastjson.annotation.JSONField;
  4 +import com.alibaba.fastjson.serializer.SerializerFeature;
3 import com.tianbo.warehouse.validate.CheckUserExist; 5 import com.tianbo.warehouse.validate.CheckUserExist;
4 import org.hibernate.validator.constraints.Length; 6 import org.hibernate.validator.constraints.Length;
5 import org.springframework.security.core.GrantedAuthority; 7 import org.springframework.security.core.GrantedAuthority;
@@ -52,8 +54,10 @@ public class USERS implements UserDetails { @@ -52,8 +54,10 @@ public class USERS implements UserDetails {
52 54
53 private Integer age; 55 private Integer age;
54 56
  57 + @JSONField(serialzeFeatures= {SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty})
55 private List<ROLE> roles; 58 private List<ROLE> roles;
56 59
  60 + @JSONField(serialzeFeatures= {SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty})
57 private List<PERMISSION> permissions; 61 private List<PERMISSION> permissions;
58 62
59 public Integer getUserId() { 63 public Integer getUserId() {
@@ -229,9 +233,11 @@ public class USERS implements UserDetails { @@ -229,9 +233,11 @@ public class USERS implements UserDetails {
229 @Override 233 @Override
230 public Collection<? extends GrantedAuthority> getAuthorities(){ 234 public Collection<? extends GrantedAuthority> getAuthorities(){
231 List<GrantedAuthority> auths = new ArrayList<>(); 235 List<GrantedAuthority> auths = new ArrayList<>();
232 - for (ROLE role : roles) {  
233 - if (null != role){  
234 - auths.add(new SimpleGrantedAuthority(role.getAuthority())); 236 + if(roles!=null && !roles.isEmpty()){
  237 + for (ROLE role : roles) {
  238 + if (null != role){
  239 + auths.add(new SimpleGrantedAuthority(role.getAuthority()));
  240 + }
235 } 241 }
236 } 242 }
237 return auths; 243 return auths;
  1 +package com.tianbo.warehouse.service;
  2 +
  3 +import com.tianbo.warehouse.model.LOG;
  4 +import com.tianbo.warehouse.model.LOGWithBLOBs;
  5 +
  6 +public interface LogService {
  7 +
  8 + int insertSelective(LOGWithBLOBs record);
  9 +}
  1 +package com.tianbo.warehouse.service.imp;
  2 +
  3 +import com.tianbo.warehouse.dao.LOGMapper;
  4 +import com.tianbo.warehouse.model.LOG;
  5 +import com.tianbo.warehouse.model.LOGWithBLOBs;
  6 +import com.tianbo.warehouse.service.LogService;
  7 +import org.springframework.beans.factory.annotation.Autowired;
  8 +import org.springframework.stereotype.Service;
  9 +
  10 +
  11 +@Service("webLog")
  12 +public class LogServiceImp implements LogService{
  13 +
  14 + @Autowired
  15 + private LOGMapper logMapper;
  16 +
  17 + @Override
  18 + public int insertSelective(LOGWithBLOBs record){
  19 + return logMapper.insertSelective(record);
  20 + }
  21 +}
  1 +package com.tianbo.warehouse.util.IO;
  2 +
  3 +import org.apache.commons.lang.ArrayUtils;
  4 +
  5 +import java.util.Arrays;
  6 +import java.util.stream.Stream;
  7 +
  8 +public abstract class StreamUtil implements Stream{
  9 +
  10 + public static <T> Stream<T> streamOf(T[] array) {
  11 + return ArrayUtils.isEmpty(array) ? Stream.empty() : Arrays.asList(array).stream();
  12 + }
  13 +}
@@ -45,6 +45,6 @@ @@ -45,6 +45,6 @@
45 <property name="enableSubPackages" value="true"/> 45 <property name="enableSubPackages" value="true"/>
46 </javaClientGenerator> 46 </javaClientGenerator>
47 <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名--> 47 <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
48 - <table tableName="permission" domainObjectName="PERMISSION" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> 48 + <table tableName="log" domainObjectName="LOG" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
49 </context> 49 </context>
50 </generatorConfiguration> 50 </generatorConfiguration>
  1 +<?xml version="1.0" encoding="UTF-8" ?>
  2 +<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3 +<mapper namespace="com.tianbo.warehouse.dao.LOGMapper" >
  4 + <resultMap id="BaseResultMap" type="com.tianbo.warehouse.model.LOG" >
  5 + <id column="logId" property="logid" jdbcType="INTEGER" />
  6 + <result column="userName" property="username" jdbcType="VARCHAR" />
  7 + <result column="ip" property="ip" jdbcType="VARCHAR" />
  8 + <result column="logCreatTime" property="logcreattime" jdbcType="TIMESTAMP" />
  9 + <result column="methodName" property="methodname" jdbcType="VARCHAR" />
  10 + <result column="modelNameCN" property="modelnamecn" jdbcType="VARCHAR" />
  11 + <result column="operateNameCN" property="operatenamecn" jdbcType="VARCHAR" />
  12 + <result column="className" property="classname" jdbcType="VARCHAR" />
  13 + </resultMap>
  14 + <resultMap id="ResultMapWithBLOBs" type="com.tianbo.warehouse.model.LOGWithBLOBs" extends="BaseResultMap" >
  15 + <result column="parameters" property="parameters" jdbcType="LONGVARCHAR" />
  16 + <result column="result" property="result" jdbcType="LONGVARCHAR" />
  17 + </resultMap>
  18 + <sql id="Base_Column_List" >
  19 + logId, userName, ip, logCreatTime, methodName, modelNameCN, operateNameCN, className
  20 + </sql>
  21 + <sql id="Blob_Column_List" >
  22 + parameters, result
  23 + </sql>
  24 + <select id="selectByPrimaryKey" resultMap="ResultMapWithBLOBs" parameterType="java.lang.Integer" >
  25 + select
  26 + <include refid="Base_Column_List" />
  27 + ,
  28 + <include refid="Blob_Column_List" />
  29 + from log
  30 + where logId = #{logid,jdbcType=INTEGER}
  31 + </select>
  32 + <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
  33 + delete from log
  34 + where logId = #{logid,jdbcType=INTEGER}
  35 + </delete>
  36 + <insert id="insert" parameterType="com.tianbo.warehouse.model.LOGWithBLOBs" >
  37 + insert into log (logId, userName, ip,
  38 + logCreatTime, methodName, modelNameCN,
  39 + operateNameCN, className, parameters,
  40 + result)
  41 + values (#{logid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{ip,jdbcType=VARCHAR},
  42 + #{logcreattime,jdbcType=TIMESTAMP}, #{methodname,jdbcType=VARCHAR}, #{modelnamecn,jdbcType=VARCHAR},
  43 + #{operatenamecn,jdbcType=VARCHAR}, #{classname,jdbcType=VARCHAR}, #{parameters,jdbcType=LONGVARCHAR},
  44 + #{result,jdbcType=LONGVARCHAR})
  45 + </insert>
  46 + <insert id="insertSelective" parameterType="com.tianbo.warehouse.model.LOGWithBLOBs" >
  47 + insert into log
  48 + <trim prefix="(" suffix=")" suffixOverrides="," >
  49 + <if test="logid != null" >
  50 + logId,
  51 + </if>
  52 + <if test="username != null" >
  53 + userName,
  54 + </if>
  55 + <if test="ip != null" >
  56 + ip,
  57 + </if>
  58 + <if test="logcreattime != null" >
  59 + logCreatTime,
  60 + </if>
  61 + <if test="methodname != null" >
  62 + methodName,
  63 + </if>
  64 + <if test="modelnamecn != null" >
  65 + modelNameCN,
  66 + </if>
  67 + <if test="operatenamecn != null" >
  68 + operateNameCN,
  69 + </if>
  70 + <if test="classname != null" >
  71 + className,
  72 + </if>
  73 + <if test="parameters != null" >
  74 + parameters,
  75 + </if>
  76 + <if test="result != null" >
  77 + result,
  78 + </if>
  79 + </trim>
  80 + <trim prefix="values (" suffix=")" suffixOverrides="," >
  81 + <if test="logid != null" >
  82 + #{logid,jdbcType=INTEGER},
  83 + </if>
  84 + <if test="username != null" >
  85 + #{username,jdbcType=VARCHAR},
  86 + </if>
  87 + <if test="ip != null" >
  88 + #{ip,jdbcType=VARCHAR},
  89 + </if>
  90 + <if test="logcreattime != null" >
  91 + #{logcreattime,jdbcType=TIMESTAMP},
  92 + </if>
  93 + <if test="methodname != null" >
  94 + #{methodname,jdbcType=VARCHAR},
  95 + </if>
  96 + <if test="modelnamecn != null" >
  97 + #{modelnamecn,jdbcType=VARCHAR},
  98 + </if>
  99 + <if test="operatenamecn != null" >
  100 + #{operatenamecn,jdbcType=VARCHAR},
  101 + </if>
  102 + <if test="classname != null" >
  103 + #{classname,jdbcType=VARCHAR},
  104 + </if>
  105 + <if test="parameters != null" >
  106 + #{parameters,jdbcType=LONGVARCHAR},
  107 + </if>
  108 + <if test="result != null" >
  109 + #{result,jdbcType=LONGVARCHAR},
  110 + </if>
  111 + </trim>
  112 + </insert>
  113 + <update id="updateByPrimaryKeySelective" parameterType="com.tianbo.warehouse.model.LOGWithBLOBs" >
  114 + update log
  115 + <set >
  116 + <if test="username != null" >
  117 + userName = #{username,jdbcType=VARCHAR},
  118 + </if>
  119 + <if test="ip != null" >
  120 + ip = #{ip,jdbcType=VARCHAR},
  121 + </if>
  122 + <if test="logcreattime != null" >
  123 + logCreatTime = #{logcreattime,jdbcType=TIMESTAMP},
  124 + </if>
  125 + <if test="methodname != null" >
  126 + methodName = #{methodname,jdbcType=VARCHAR},
  127 + </if>
  128 + <if test="modelnamecn != null" >
  129 + modelNameCN = #{modelnamecn,jdbcType=VARCHAR},
  130 + </if>
  131 + <if test="operatenamecn != null" >
  132 + operateNameCN = #{operatenamecn,jdbcType=VARCHAR},
  133 + </if>
  134 + <if test="classname != null" >
  135 + className = #{classname,jdbcType=VARCHAR},
  136 + </if>
  137 + <if test="parameters != null" >
  138 + parameters = #{parameters,jdbcType=LONGVARCHAR},
  139 + </if>
  140 + <if test="result != null" >
  141 + result = #{result,jdbcType=LONGVARCHAR},
  142 + </if>
  143 + </set>
  144 + where logId = #{logid,jdbcType=INTEGER}
  145 + </update>
  146 + <update id="updateByPrimaryKeyWithBLOBs" parameterType="com.tianbo.warehouse.model.LOGWithBLOBs" >
  147 + update log
  148 + set userName = #{username,jdbcType=VARCHAR},
  149 + ip = #{ip,jdbcType=VARCHAR},
  150 + logCreatTime = #{logcreattime,jdbcType=TIMESTAMP},
  151 + methodName = #{methodname,jdbcType=VARCHAR},
  152 + modelNameCN = #{modelnamecn,jdbcType=VARCHAR},
  153 + operateNameCN = #{operatenamecn,jdbcType=VARCHAR},
  154 + className = #{classname,jdbcType=VARCHAR},
  155 + parameters = #{parameters,jdbcType=LONGVARCHAR},
  156 + result = #{result,jdbcType=LONGVARCHAR}
  157 + where logId = #{logid,jdbcType=INTEGER}
  158 + </update>
  159 + <update id="updateByPrimaryKey" parameterType="com.tianbo.warehouse.model.LOG" >
  160 + update log
  161 + set userName = #{username,jdbcType=VARCHAR},
  162 + ip = #{ip,jdbcType=VARCHAR},
  163 + logCreatTime = #{logcreattime,jdbcType=TIMESTAMP},
  164 + methodName = #{methodname,jdbcType=VARCHAR},
  165 + modelNameCN = #{modelnamecn,jdbcType=VARCHAR},
  166 + operateNameCN = #{operatenamecn,jdbcType=VARCHAR},
  167 + className = #{classname,jdbcType=VARCHAR}
  168 + where logId = #{logid,jdbcType=INTEGER}
  169 + </update>
  170 +</mapper>