作者 朱兆平

日志处理

package com.tianbo.warehouse.annotation;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
/**
* 自定义日志注解
*/
public @interface LogAnnotation {
/**模块名称*/
String moduleName() default "";
/**操作内容*/
String operate() default "";
}
... ...
package com.tianbo.warehouse.annotation;
import com.alibaba.fastjson.JSON;
import com.tianbo.warehouse.model.LOGWithBLOBs;
import com.tianbo.warehouse.service.LogService;
import com.tianbo.warehouse.util.IO.StreamUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
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.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Aspect
@Component
public class LogAnnotationAOP {
@Autowired
private LogService logService;
private LOGWithBLOBs log;
@Pointcut("@annotation(com.tianbo.warehouse.annotation.LogAnnotation)")
public void annotationPointCut(){
}
@Before("annotationPointCut()")
public void before(JoinPoint point){
//获取当前登录用户信息
try{
UserDetails userDetails =(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String requestRemoteAddr = request.getRemoteAddr();
log.setIp(requestRemoteAddr);
log.setUsername(userDetails.getUsername());
}catch (Exception e){
e.printStackTrace();
}
try{
String targetName = point.getTarget().getClass().getName();
Class targetClass = Class.forName(targetName);
MethodSignature signature = (MethodSignature) point.getSignature();
Method method= signature.getMethod();
LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
System.out.print("打印:"+annotation.moduleName()+" 开始前");
String methodName = point.getSignature().getName();
// Method[] methods = targetClass.getMethods();
if(annotation != null){
log.setModelnamecn(annotation.moduleName());
log.setOperatenamecn(annotation.operate());
}
log.setClassname(targetName);
log.setMethodname(methodName);
// 获得参数列表
Object[] params = point.getArgs();
if(params.length>0){
//序列化时过滤掉request和response,参考资料为:https://blog.csdn.net/hbn1326317071/article/details/83818059
List<Object> logArgs = StreamUtil.streamOf(params)
.filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse) && !(arg instanceof BindingResult)))
.collect(Collectors.toList());
//将参数列表转成JSON存储
log.setParameters(JSON.toJSONString(logArgs));
}
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
@Around("annotationPointCut()")
public Object advice(ProceedingJoinPoint joinPoint){
System.out.println("通知之开始");
log = new LOGWithBLOBs();
Object retmsg=null;
try {
retmsg=joinPoint.proceed();
System.err.println("++++++++"+retmsg);
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("通知之结束");
return retmsg;
}
@After("annotationPointCut()")
public void after(){
System.out.println("after方法执行后");
}
/**
* 方法正常完成后执行方法
* @param retmsg 这里的retmsg= advice中的Object retmsg
*/
@AfterReturning(returning = "retmsg",pointcut="annotationPointCut()")
public void afterReturn(Object retmsg) throws Throwable{
// 处理完请求,返回内容
log.setResult(JSON.toJSONString(retmsg));
logService.insertSelective(log);
}
}
... ...
package com.tianbo.warehouse.controller;
import com.github.pagehelper.PageInfo;
import com.tianbo.warehouse.annotation.LogAnnotation;
import com.tianbo.warehouse.annotation.UserPasswordMd5;
import com.tianbo.warehouse.controller.response.ResultJson;
import com.tianbo.warehouse.model.USERS;
... ... @@ -50,6 +51,7 @@ public class UserController {
}
@UserPasswordMd5
@LogAnnotation(moduleName = "用户管理",operate = "用户添加")
@PostMapping("/user/add")
public ResultJson addUser(@RequestBody @Valid USERS user, HttpServletRequest request, HttpServletResponse response, BindingResult bindingResult){
... ...
package com.tianbo.warehouse.dao;
import com.tianbo.warehouse.model.LOG;
import com.tianbo.warehouse.model.LOGWithBLOBs;
public interface LOGMapper {
int deleteByPrimaryKey(Integer logid);
int insert(LOGWithBLOBs record);
int insertSelective(LOGWithBLOBs record);
LOGWithBLOBs selectByPrimaryKey(Integer logid);
int updateByPrimaryKeySelective(LOGWithBLOBs record);
int updateByPrimaryKeyWithBLOBs(LOGWithBLOBs record);
int updateByPrimaryKey(LOG record);
}
\ No newline at end of file
... ...
package com.tianbo.warehouse.model;
import java.util.Date;
public class LOG {
private Integer logid;
private String username;
private String ip;
private Date logcreattime;
private String methodname;
private String modelnamecn;
private String operatenamecn;
private String classname;
public Integer getLogid() {
return logid;
}
public void setLogid(Integer logid) {
this.logid = logid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip == null ? null : ip.trim();
}
public Date getLogcreattime() {
return logcreattime;
}
public void setLogcreattime(Date logcreattime) {
this.logcreattime = logcreattime;
}
public String getMethodname() {
return methodname;
}
public void setMethodname(String methodname) {
this.methodname = methodname == null ? null : methodname.trim();
}
public String getModelnamecn() {
return modelnamecn;
}
public void setModelnamecn(String modelnamecn) {
this.modelnamecn = modelnamecn == null ? null : modelnamecn.trim();
}
public String getOperatenamecn() {
return operatenamecn;
}
public void setOperatenamecn(String operatenamecn) {
this.operatenamecn = operatenamecn == null ? null : operatenamecn.trim();
}
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname == null ? null : classname.trim();
}
}
\ No newline at end of file
... ...
package com.tianbo.warehouse.model;
public class LOGWithBLOBs extends LOG {
private String parameters;
private String result;
public String getParameters() {
return parameters;
}
public void setParameters(String parameters) {
this.parameters = parameters == null ? null : parameters.trim();
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result == null ? null : result.trim();
}
}
\ No newline at end of file
... ...
package com.tianbo.warehouse.model;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tianbo.warehouse.validate.CheckUserExist;
import org.hibernate.validator.constraints.Length;
import org.springframework.security.core.GrantedAuthority;
... ... @@ -52,8 +54,10 @@ public class USERS implements UserDetails {
private Integer age;
@JSONField(serialzeFeatures= {SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty})
private List<ROLE> roles;
@JSONField(serialzeFeatures= {SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty})
private List<PERMISSION> permissions;
public Integer getUserId() {
... ... @@ -229,11 +233,13 @@ public class USERS implements UserDetails {
@Override
public Collection<? extends GrantedAuthority> getAuthorities(){
List<GrantedAuthority> auths = new ArrayList<>();
if(roles!=null && !roles.isEmpty()){
for (ROLE role : roles) {
if (null != role){
auths.add(new SimpleGrantedAuthority(role.getAuthority()));
}
}
}
return auths;
}
}
\ No newline at end of file
... ...
package com.tianbo.warehouse.service;
import com.tianbo.warehouse.model.LOG;
import com.tianbo.warehouse.model.LOGWithBLOBs;
public interface LogService {
int insertSelective(LOGWithBLOBs record);
}
... ...
package com.tianbo.warehouse.service.imp;
import com.tianbo.warehouse.dao.LOGMapper;
import com.tianbo.warehouse.model.LOG;
import com.tianbo.warehouse.model.LOGWithBLOBs;
import com.tianbo.warehouse.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("webLog")
public class LogServiceImp implements LogService{
@Autowired
private LOGMapper logMapper;
@Override
public int insertSelective(LOGWithBLOBs record){
return logMapper.insertSelective(record);
}
}
... ...
package com.tianbo.warehouse.util.IO;
import org.apache.commons.lang.ArrayUtils;
import java.util.Arrays;
import java.util.stream.Stream;
public abstract class StreamUtil implements Stream{
public static <T> Stream<T> streamOf(T[] array) {
return ArrayUtils.isEmpty(array) ? Stream.empty() : Arrays.asList(array).stream();
}
}
... ...
... ... @@ -45,6 +45,6 @@
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="permission" domainObjectName="PERMISSION" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
<table tableName="log" domainObjectName="LOG" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
\ No newline at end of file
... ...
<?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.tianbo.warehouse.dao.LOGMapper" >
<resultMap id="BaseResultMap" type="com.tianbo.warehouse.model.LOG" >
<id column="logId" property="logid" jdbcType="INTEGER" />
<result column="userName" property="username" jdbcType="VARCHAR" />
<result column="ip" property="ip" jdbcType="VARCHAR" />
<result column="logCreatTime" property="logcreattime" jdbcType="TIMESTAMP" />
<result column="methodName" property="methodname" jdbcType="VARCHAR" />
<result column="modelNameCN" property="modelnamecn" jdbcType="VARCHAR" />
<result column="operateNameCN" property="operatenamecn" jdbcType="VARCHAR" />
<result column="className" property="classname" jdbcType="VARCHAR" />
</resultMap>
<resultMap id="ResultMapWithBLOBs" type="com.tianbo.warehouse.model.LOGWithBLOBs" extends="BaseResultMap" >
<result column="parameters" property="parameters" jdbcType="LONGVARCHAR" />
<result column="result" property="result" jdbcType="LONGVARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
logId, userName, ip, logCreatTime, methodName, modelNameCN, operateNameCN, className
</sql>
<sql id="Blob_Column_List" >
parameters, result
</sql>
<select id="selectByPrimaryKey" resultMap="ResultMapWithBLOBs" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
,
<include refid="Blob_Column_List" />
from log
where logId = #{logid,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from log
where logId = #{logid,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.tianbo.warehouse.model.LOGWithBLOBs" >
insert into log (logId, userName, ip,
logCreatTime, methodName, modelNameCN,
operateNameCN, className, parameters,
result)
values (#{logid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{ip,jdbcType=VARCHAR},
#{logcreattime,jdbcType=TIMESTAMP}, #{methodname,jdbcType=VARCHAR}, #{modelnamecn,jdbcType=VARCHAR},
#{operatenamecn,jdbcType=VARCHAR}, #{classname,jdbcType=VARCHAR}, #{parameters,jdbcType=LONGVARCHAR},
#{result,jdbcType=LONGVARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.tianbo.warehouse.model.LOGWithBLOBs" >
insert into log
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="logid != null" >
logId,
</if>
<if test="username != null" >
userName,
</if>
<if test="ip != null" >
ip,
</if>
<if test="logcreattime != null" >
logCreatTime,
</if>
<if test="methodname != null" >
methodName,
</if>
<if test="modelnamecn != null" >
modelNameCN,
</if>
<if test="operatenamecn != null" >
operateNameCN,
</if>
<if test="classname != null" >
className,
</if>
<if test="parameters != null" >
parameters,
</if>
<if test="result != null" >
result,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="logid != null" >
#{logid,jdbcType=INTEGER},
</if>
<if test="username != null" >
#{username,jdbcType=VARCHAR},
</if>
<if test="ip != null" >
#{ip,jdbcType=VARCHAR},
</if>
<if test="logcreattime != null" >
#{logcreattime,jdbcType=TIMESTAMP},
</if>
<if test="methodname != null" >
#{methodname,jdbcType=VARCHAR},
</if>
<if test="modelnamecn != null" >
#{modelnamecn,jdbcType=VARCHAR},
</if>
<if test="operatenamecn != null" >
#{operatenamecn,jdbcType=VARCHAR},
</if>
<if test="classname != null" >
#{classname,jdbcType=VARCHAR},
</if>
<if test="parameters != null" >
#{parameters,jdbcType=LONGVARCHAR},
</if>
<if test="result != null" >
#{result,jdbcType=LONGVARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.tianbo.warehouse.model.LOGWithBLOBs" >
update log
<set >
<if test="username != null" >
userName = #{username,jdbcType=VARCHAR},
</if>
<if test="ip != null" >
ip = #{ip,jdbcType=VARCHAR},
</if>
<if test="logcreattime != null" >
logCreatTime = #{logcreattime,jdbcType=TIMESTAMP},
</if>
<if test="methodname != null" >
methodName = #{methodname,jdbcType=VARCHAR},
</if>
<if test="modelnamecn != null" >
modelNameCN = #{modelnamecn,jdbcType=VARCHAR},
</if>
<if test="operatenamecn != null" >
operateNameCN = #{operatenamecn,jdbcType=VARCHAR},
</if>
<if test="classname != null" >
className = #{classname,jdbcType=VARCHAR},
</if>
<if test="parameters != null" >
parameters = #{parameters,jdbcType=LONGVARCHAR},
</if>
<if test="result != null" >
result = #{result,jdbcType=LONGVARCHAR},
</if>
</set>
where logId = #{logid,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKeyWithBLOBs" parameterType="com.tianbo.warehouse.model.LOGWithBLOBs" >
update log
set userName = #{username,jdbcType=VARCHAR},
ip = #{ip,jdbcType=VARCHAR},
logCreatTime = #{logcreattime,jdbcType=TIMESTAMP},
methodName = #{methodname,jdbcType=VARCHAR},
modelNameCN = #{modelnamecn,jdbcType=VARCHAR},
operateNameCN = #{operatenamecn,jdbcType=VARCHAR},
className = #{classname,jdbcType=VARCHAR},
parameters = #{parameters,jdbcType=LONGVARCHAR},
result = #{result,jdbcType=LONGVARCHAR}
where logId = #{logid,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.tianbo.warehouse.model.LOG" >
update log
set userName = #{username,jdbcType=VARCHAR},
ip = #{ip,jdbcType=VARCHAR},
logCreatTime = #{logcreattime,jdbcType=TIMESTAMP},
methodName = #{methodname,jdbcType=VARCHAR},
modelNameCN = #{modelnamecn,jdbcType=VARCHAR},
operateNameCN = #{operatenamecn,jdbcType=VARCHAR},
className = #{classname,jdbcType=VARCHAR}
where logId = #{logid,jdbcType=INTEGER}
</update>
</mapper>
\ No newline at end of file
... ...