码迷,mamicode.com
首页 > 其他好文 > 详细

简易的用户操作日志记录

时间:2019-10-17 16:03:07      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:common   framework   slf4j   element   json   开始   返回   sage   ase   

记录系统内用户的操作日志。

1.日志类

技术图片
public class SysLog {
    /**
     * 主键
     */
    private String id;
    /**
     * 操作开始时间
     */
    private Date createTime;
    /**
     * 操作结束时间
     */
    private Date endTime;
    /**
     * 执行耗时
     */
    private long excuteTime;
    /**
     * 接口地址
     */
    private String url;
    /**
     * 请求参数
     */
    private String params;
    /**
     * 操作结果代码
     */
    private String code;
    /**
     * 接口名
     */
    private String targetName;
    /**
     * 接口方法
     */
    private String methodName;
    /**
     * 业务类型
     */
    private String businessType;
    /**
     * 操作名称
     */
    private String operationName;
    /**
     * 异常原因
     */
    private String reason;
    /**
     * 请求ip
     */
    private String ip;
    /**
     * 操作人userid
     */
    private String userId;
    /**
     * 操作人名称
     */
    private String userName;

    public String getId() {
        return id;
    }

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

    public Date getCreateTime() {
        return createTime;
    }

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

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getParams() {
        return params;
    }

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

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getTargetName() {
        return targetName;
    }

    public void setTargetName(String targetName) {
        this.targetName = targetName;
    }

    public String getMethodName() {
        return methodName;
    }

    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }

    public String getBusinessType() {
        return businessType;
    }

    public void setBusinessType(String businessType) {
        this.businessType = businessType;
    }

    public String getOperationName() {
        return operationName;
    }

    public void setOperationName(String operationName) {
        this.operationName = operationName;
    }

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public String getIp() {
        return ip;
    }

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

    public String getUserId() {
        return userId;
    }

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

    public String getUserName() {
        return userName;
    }

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

    public Date getEndTime() {
        return endTime;
    }

    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }

    public long getExcuteTime() {
        return excuteTime;
    }

    public void setExcuteTime(long excuteTime) {
        this.excuteTime = excuteTime;
    }

    @Override
    public String toString() {
        return "SysLog{" +
                "id=‘" + id + \‘ +
                ", createTime=" + createTime +
                ", endTime=" + endTime +
                ", excuteTime=" + excuteTime +
                ", url=‘" + url + \‘ +
                ", params=‘" + params + \‘ +
                ", code=‘" + code + \‘ +
                ", targetName=‘" + targetName + \‘ +
                ", methodName=‘" + methodName + \‘ +
                ", businessType=‘" + businessType + \‘ +
                ", operationName=‘" + operationName + \‘ +
                ", reason=‘" + reason + \‘ +
                ", ip=‘" + ip + \‘ +
                ", userId=‘" + userId + \‘ +
                ", userName=‘" + userName + \‘ +
                };
    }
}
View Code

 

2.日志注解

技术图片
package com.ax.logger.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface SystemLogAnnotation {
    //  业务类型
    String businessType() default "";

    // 操作名称
    String operationName() default "";
}
View Code

 

3.具体执行代码

技术图片
package com.ax.logger;

import com.ax.constants.Constants;
import com.ax.entity.system.SysLog;
import com.ax.entity.system.SysUser;
import com.ax.entity.system.SysUserVo;
import com.ax.logger.annotation.SystemLogAnnotation;
import com.ax.result.JsonResult;
import com.ax.result.ResultCode;
import com.ax.service.SystemClient;
import com.ax.util.JsonUtils;
import com.ax.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
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 java.util.Arrays;
import java.util.Date;


/**
 * 日志切面类
 */
@Aspect
@Component
public class LogAspect {

    private final static Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    SystemClient systemClient;

    private SysLog sysLog = new SysLog();

    /**
     * 功能描述: 切点
     */    @Pointcut("@annotation(com.ax.logger.annotation.SystemLogAnnotation)")
    public void executePointCut() {
    }

    /**
     * 功能描述: 请求前执行
     */
    @Before("executePointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //  主键
        sysLog.setId(StringUtil.getId());
        //  操作时间
        sysLog.setCreateTime(new Date());
        //  接口地址
        sysLog.setUrl(request.getRequestURL().toString());
        //  接口名
        sysLog.setTargetName(joinPoint.getTarget().getClass().getName());
        //  接口方法
        sysLog.setMethodName(joinPoint.getSignature().getName());
        //  操作名称和业务类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        SystemLogAnnotation annotation = signature.getMethod().getAnnotation(SystemLogAnnotation.class);
        sysLog.setOperationName(annotation.operationName());
        sysLog.setBusinessType(annotation.businessType());
        //  请求参数
        sysLog.setParams(JsonUtils.objectToJson(joinPoint.getArgs()));
        //  请求ip
        sysLog.setIp(request.getRemoteAddr());
        //  获取头部token
        String accessToken = request.getHeader("x-auth-token");
        if (StringUtils.isNotEmpty(accessToken)) {
            //  通过token获取用户对象
            String sessionKey = Constants.SESSION_KEY_PREFIX + accessToken;
            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            SysUser SysUser = JsonUtils.jsonToPojo(ops.get(sessionKey), SysUser.class);
            //  操作人userid
            sysLog.setUserId(SysUser.getUserId());
            //  操作人姓名
            sysLog.setUserName(SysUser.getUsername());
        }
    }

    /**
     * 请求后执行
     */
    @AfterReturning(returning = "ret", pointcut = "executePointCut()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求,返回内容
        JsonResult result = (JsonResult) ret;
        sysLog.setCode(result.getCode());
        //  方法结束时间
        sysLog.setEndTime(new Date());
        //  计算方法执行时间
        long excuteTime = sysLog.getEndTime().getTime() - sysLog.getCreateTime().getTime();
        sysLog.setExcuteTime(excuteTime);
        // 异常原因
        if (!StringUtils.equals(result.getCode(), ResultCode.SUCCESS.code)) {
            sysLog.setReason(result.getMessage());
        }
        //保存日志
        systemClient.saveLog(sysLog);
        System.out.println(sysLog);
    }

}
View Code

 

4.具体实现

技术图片
@PostMapping("/saveBaseInfo")
    @SystemLogAnnotation(businessType = "专家信息", operationName = "修改专家信息")
    public JsonResult saveBaseInfo(@RequestBody ExpertBaseInfo expertBaseInfo) {
        ...
    }
View Code

 

简易的用户操作日志记录

标签:common   framework   slf4j   element   json   开始   返回   sage   ase   

原文地址:https://www.cnblogs.com/shiblog/p/11692279.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!