实现日志落库从0到1

第一步 创建日志实体类和数据库

创建数据库
CREATE TABLE `aop_utils` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `create_by` varchar(20) DEFAULT NULL COMMENT '创建人',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `del_flag` bit(1) DEFAULT b'0' COMMENT '0未删除 ,1已删除',
  `update_by` varchar(20) DEFAULT NULL COMMENT '更新人',
  `update_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `user_id` int(11) DEFAULT NULL COMMENT '操作用户id',
  `ip` varchar(255) DEFAULT NULL COMMENT '请求ip',
  `application_name` varchar(255) DEFAULT NULL COMMENT '模块名称(微服务名称)',
  `name` varchar(255) DEFAULT NULL COMMENT '操作用户名称',
  `request_param` text COMMENT '请求参数',
  `request_description` varchar(255) DEFAULT NULL COMMENT '请求描述',
  `request_url` varchar(255) DEFAULT NULL COMMENT '请求路径',
  `response_msg` text COMMENT '返回信息',
  `org_id` bigint(20) DEFAULT NULL COMMENT '日志用户的机构id',
  `mobile_phone` varchar(100) DEFAULT NULL COMMENT '手机号',
  `log_type` int(11) DEFAULT NULL COMMENT '(0 登录 1 增加 2 删除 3 修改  4 查询   )',
  `request_method` varchar(20) DEFAULT NULL COMMENT '请求方法',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;
创建实体类

import java.io.Serializable;
import java.util.Date;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

/**
 * @author 
 * 
 */
@Data
@TableName(value = "aop_utils")
public class AopUtilsPojo implements Serializable {
    /**
     * 主键
     */
    @TableId(type = IdType.AUTO)
    private Long id;
    /**
     * 创建人
     */
    private String createBy;

    /**
     * 创建时间
     */
    private Date createTime;

    /**
     * 0未删除 ,1已删除
     */
    private Boolean delFlag;

    /**
     * 更新人
     */
    private String updateBy;

    /**
     * 更新时间
     */
    private Date updateTime;

    /**
     * 操作用户id
     */
    private Integer userId;

    /**
     * 请求ip
     */
    private String ip;

    /**
     * 模块名称(微服务名称)
     */
    private String applicationName;

    /**
     * 操作用户名称
     */
    private String name;

    /**
     * 请求描述
     */
    private String requestDescription;

    /**
     * 请求路径
     */
    private String requestUrl;
    /**
     * 请求参数
     */
    private String requestParam;

    /**
     * 日志用户的机构id
     */
    private Long orgId;

    /**
     * 手机号
     */
    private String mobilePhone;

    /**
     * (0 登录 1 增加 2 删除 3 修改  4 查询   )
     */
    private Integer logType;
    /*
    * 返回信息
    */
    private String responseMsg;
    /*
     * 请求方法
     */
    private String requestMethod;

    private static final long serialVersionUID = 1L;
}

第二步 日志自定义注解

注解
/**
 * @author: Jay
 * @description: 日志接口注解
 * @create: 2021-10-12 10:44
 **/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogOperation {
    int logType() ;

    String  description() default "";

    String value() default "";
    /**
     * 记录去除
     * @return
     */
    String[] exclude() default {};
}

第三步 模拟获取SessionUser()类

Session

/**
 * @author: Jay
 * @description: d
 * @create: 2021-10-12 10:57
 **/
public interface Session {
    String getSessionId();

    void invalidate();

    void setAttribute(String var1, String var2);

    void setAttribute(String var1, Integer var2);

    void setAttribute(String var1, Long var2);

    void setAttribute(String var1, Date var2);

    void setAttribute(String var1, Boolean var2);

    void setAttribute(String var1, SessionUser var2);

    Object getAttribute(String var1);

    void removeAttribute(String var1);

    boolean isNew();
}
SessionUser
/**
 * @description: SessionUser
 * @author: Jay
 * @create: 2021-10-12 10:56
 **/
public class SessionUser {
    public static final String SESSION_USER_KEY = "SessionUser";
    private String id;
    private String ossType;
    private String orgId;
    private String loginName;
    private String name;
    private String avator;
    private String mobilePhone;
    private String telPhone;
    private String email;
    private String department;
    private String employeeNum;
    private String sex;
    private String status;
    private String description;
    private Date lastLoginTime;
    private String lastLoginAddress;
    private Date createTime;
    private Date updateTime;
    private Set<String> roles;
    private Set<String> perms;
    private String wechatOpenId;
    private String wechatEpNum;
    private String wechatNickName;
    private String wechatHeadImgUrl;
    private String authName;
    private String authIdNum;

    public SessionUser() {
    }

    public static SessionUser getSessionUser(Session session) {
        if (session == null) {
            return null;
        } else {
            Object object = session.getAttribute("SessionUser");
            return !(object instanceof SessionUser) ? null : (SessionUser)object;
        }
    }

    public static void setSessionUser(Session session, SessionUser user) {
        if (session != null && user != null) {
            session.setAttribute("SessionUser", user);
        }
    }

    public boolean isAdmin() {
        return this.hasRole("admin");
    }

    public boolean hasRole(String role) {
        return has(role, this.roles);
    }

    public boolean hasPermission(String permission) {
        return has(permission, this.perms);
    }

    private static boolean has(String value, Set<String> collections) {
        if (StringUtils.isBlank(value)) {
            return false;
        } else {
            return collections != null && collections.size() != 0 ? collections.contains(value) : false;
        }
    }

    public String getId() {
        return this.id;
    }

    public String getOssType() {
        return this.ossType;
    }

    public String getOrgId() {
        return this.orgId;
    }

    public String getLoginName() {
        return this.loginName;
    }

    public String getName() {
        return this.name;
    }

    public String getAvator() {
        return this.avator;
    }

    public String getMobilePhone() {
        return this.mobilePhone;
    }

    public String getTelPhone() {
        return this.telPhone;
    }

    public String getEmail() {
        return this.email;
    }

    public String getDepartment() {
        return this.department;
    }

    public String getEmployeeNum() {
        return this.employeeNum;
    }

    public String getSex() {
        return this.sex;
    }

    public String getStatus() {
        return this.status;
    }

    public String getDescription() {
        return this.description;
    }

    public Date getLastLoginTime() {
        return this.lastLoginTime;
    }

    public String getLastLoginAddress() {
        return this.lastLoginAddress;
    }

    public Date getCreateTime() {
        return this.createTime;
    }

    public Date getUpdateTime() {
        return this.updateTime;
    }

    public Set<String> getRoles() {
        return this.roles;
    }

    public Set<String> getPerms() {
        return this.perms;
    }

    public String getWechatOpenId() {
        return this.wechatOpenId;
    }

    public String getWechatEpNum() {
        return this.wechatEpNum;
    }

    public String getWechatNickName() {
        return this.wechatNickName;
    }

    public String getWechatHeadImgUrl() {
        return this.wechatHeadImgUrl;
    }

    public String getAuthName() {
        return this.authName;
    }

    public String getAuthIdNum() {
        return this.authIdNum;
    }

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

    public void setOssType(String ossType) {
        this.ossType = ossType;
    }

    public void setOrgId(String orgId) {
        this.orgId = orgId;
    }

    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAvator(String avator) {
        this.avator = avator;
    }

    public void setMobilePhone(String mobilePhone) {
        this.mobilePhone = mobilePhone;
    }

    public void setTelPhone(String telPhone) {
        this.telPhone = telPhone;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public void setEmployeeNum(String employeeNum) {
        this.employeeNum = employeeNum;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setLastLoginTime(Date lastLoginTime) {
        this.lastLoginTime = lastLoginTime;
    }

    public void setLastLoginAddress(String lastLoginAddress) {
        this.lastLoginAddress = lastLoginAddress;
    }

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

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public void setRoles(Set<String> roles) {
        this.roles = roles;
    }

    public void setPerms(Set<String> perms) {
        this.perms = perms;
    }

    public void setWechatOpenId(String wechatOpenId) {
        this.wechatOpenId = wechatOpenId;
    }

    public void setWechatEpNum(String wechatEpNum) {
        this.wechatEpNum = wechatEpNum;
    }

    public void setWechatNickName(String wechatNickName) {
        this.wechatNickName = wechatNickName;
    }

    public void setWechatHeadImgUrl(String wechatHeadImgUrl) {
        this.wechatHeadImgUrl = wechatHeadImgUrl;
    }

    public void setAuthName(String authName) {
        this.authName = authName;
    }

    public void setAuthIdNum(String authIdNum) {
        this.authIdNum = authIdNum;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof SessionUser)) {
            return false;
        } else {
            SessionUser other = (SessionUser)o;
            if (!other.canEqual(this)) {
                return false;
            } else {
                Object this$id = this.getId();
                Object other$id = other.getId();
                if (this$id == null) {
                    if (other$id != null) {
                        return false;
                    }
                } else if (!this$id.equals(other$id)) {
                    return false;
                }

                Object this$ossType = this.getOssType();
                Object other$ossType = other.getOssType();
                if (this$ossType == null) {
                    if (other$ossType != null) {
                        return false;
                    }
                } else if (!this$ossType.equals(other$ossType)) {
                    return false;
                }

                Object this$orgId = this.getOrgId();
                Object other$orgId = other.getOrgId();
                if (this$orgId == null) {
                    if (other$orgId != null) {
                        return false;
                    }
                } else if (!this$orgId.equals(other$orgId)) {
                    return false;
                }

                label302: {
                    Object this$loginName = this.getLoginName();
                    Object other$loginName = other.getLoginName();
                    if (this$loginName == null) {
                        if (other$loginName == null) {
                            break label302;
                        }
                    } else if (this$loginName.equals(other$loginName)) {
                        break label302;
                    }

                    return false;
                }

                label295: {
                    Object this$name = this.getName();
                    Object other$name = other.getName();
                    if (this$name == null) {
                        if (other$name == null) {
                            break label295;
                        }
                    } else if (this$name.equals(other$name)) {
                        break label295;
                    }

                    return false;
                }

                Object this$avator = this.getAvator();
                Object other$avator = other.getAvator();
                if (this$avator == null) {
                    if (other$avator != null) {
                        return false;
                    }
                } else if (!this$avator.equals(other$avator)) {
                    return false;
                }

                label281: {
                    Object this$mobilePhone = this.getMobilePhone();
                    Object other$mobilePhone = other.getMobilePhone();
                    if (this$mobilePhone == null) {
                        if (other$mobilePhone == null) {
                            break label281;
                        }
                    } else if (this$mobilePhone.equals(other$mobilePhone)) {
                        break label281;
                    }

                    return false;
                }

                label274: {
                    Object this$telPhone = this.getTelPhone();
                    Object other$telPhone = other.getTelPhone();
                    if (this$telPhone == null) {
                        if (other$telPhone == null) {
                            break label274;
                        }
                    } else if (this$telPhone.equals(other$telPhone)) {
                        break label274;
                    }

                    return false;
                }

                Object this$email = this.getEmail();
                Object other$email = other.getEmail();
                if (this$email == null) {
                    if (other$email != null) {
                        return false;
                    }
                } else if (!this$email.equals(other$email)) {
                    return false;
                }

                Object this$department = this.getDepartment();
                Object other$department = other.getDepartment();
                if (this$department == null) {
                    if (other$department != null) {
                        return false;
                    }
                } else if (!this$department.equals(other$department)) {
                    return false;
                }

                label253: {
                    Object this$employeeNum = this.getEmployeeNum();
                    Object other$employeeNum = other.getEmployeeNum();
                    if (this$employeeNum == null) {
                        if (other$employeeNum == null) {
                            break label253;
                        }
                    } else if (this$employeeNum.equals(other$employeeNum)) {
                        break label253;
                    }

                    return false;
                }

                label246: {
                    Object this$sex = this.getSex();
                    Object other$sex = other.getSex();
                    if (this$sex == null) {
                        if (other$sex == null) {
                            break label246;
                        }
                    } else if (this$sex.equals(other$sex)) {
                        break label246;
                    }

                    return false;
                }

                Object this$status = this.getStatus();
                Object other$status = other.getStatus();
                if (this$status == null) {
                    if (other$status != null) {
                        return false;
                    }
                } else if (!this$status.equals(other$status)) {
                    return false;
                }

                label232: {
                    Object this$description = this.getDescription();
                    Object other$description = other.getDescription();
                    if (this$description == null) {
                        if (other$description == null) {
                            break label232;
                        }
                    } else if (this$description.equals(other$description)) {
                        break label232;
                    }

                    return false;
                }

                Object this$lastLoginTime = this.getLastLoginTime();
                Object other$lastLoginTime = other.getLastLoginTime();
                if (this$lastLoginTime == null) {
                    if (other$lastLoginTime != null) {
                        return false;
                    }
                } else if (!this$lastLoginTime.equals(other$lastLoginTime)) {
                    return false;
                }

                label218: {
                    Object this$lastLoginAddress = this.getLastLoginAddress();
                    Object other$lastLoginAddress = other.getLastLoginAddress();
                    if (this$lastLoginAddress == null) {
                        if (other$lastLoginAddress == null) {
                            break label218;
                        }
                    } else if (this$lastLoginAddress.equals(other$lastLoginAddress)) {
                        break label218;
                    }

                    return false;
                }

                Object this$createTime = this.getCreateTime();
                Object other$createTime = other.getCreateTime();
                if (this$createTime == null) {
                    if (other$createTime != null) {
                        return false;
                    }
                } else if (!this$createTime.equals(other$createTime)) {
                    return false;
                }

                Object this$updateTime = this.getUpdateTime();
                Object other$updateTime = other.getUpdateTime();
                if (this$updateTime == null) {
                    if (other$updateTime != null) {
                        return false;
                    }
                } else if (!this$updateTime.equals(other$updateTime)) {
                    return false;
                }

                Object this$roles = this.getRoles();
                Object other$roles = other.getRoles();
                if (this$roles == null) {
                    if (other$roles != null) {
                        return false;
                    }
                } else if (!this$roles.equals(other$roles)) {
                    return false;
                }

                label190: {
                    Object this$perms = this.getPerms();
                    Object other$perms = other.getPerms();
                    if (this$perms == null) {
                        if (other$perms == null) {
                            break label190;
                        }
                    } else if (this$perms.equals(other$perms)) {
                        break label190;
                    }

                    return false;
                }

                label183: {
                    Object this$wechatOpenId = this.getWechatOpenId();
                    Object other$wechatOpenId = other.getWechatOpenId();
                    if (this$wechatOpenId == null) {
                        if (other$wechatOpenId == null) {
                            break label183;
                        }
                    } else if (this$wechatOpenId.equals(other$wechatOpenId)) {
                        break label183;
                    }

                    return false;
                }

                Object this$wechatEpNum = this.getWechatEpNum();
                Object other$wechatEpNum = other.getWechatEpNum();
                if (this$wechatEpNum == null) {
                    if (other$wechatEpNum != null) {
                        return false;
                    }
                } else if (!this$wechatEpNum.equals(other$wechatEpNum)) {
                    return false;
                }

                label169: {
                    Object this$wechatNickName = this.getWechatNickName();
                    Object other$wechatNickName = other.getWechatNickName();
                    if (this$wechatNickName == null) {
                        if (other$wechatNickName == null) {
                            break label169;
                        }
                    } else if (this$wechatNickName.equals(other$wechatNickName)) {
                        break label169;
                    }

                    return false;
                }

                label162: {
                    Object this$wechatHeadImgUrl = this.getWechatHeadImgUrl();
                    Object other$wechatHeadImgUrl = other.getWechatHeadImgUrl();
                    if (this$wechatHeadImgUrl == null) {
                        if (other$wechatHeadImgUrl == null) {
                            break label162;
                        }
                    } else if (this$wechatHeadImgUrl.equals(other$wechatHeadImgUrl)) {
                        break label162;
                    }

                    return false;
                }

                Object this$authName = this.getAuthName();
                Object other$authName = other.getAuthName();
                if (this$authName == null) {
                    if (other$authName != null) {
                        return false;
                    }
                } else if (!this$authName.equals(other$authName)) {
                    return false;
                }

                Object this$authIdNum = this.getAuthIdNum();
                Object other$authIdNum = other.getAuthIdNum();
                if (this$authIdNum == null) {
                    if (other$authIdNum != null) {
                        return false;
                    }
                } else if (!this$authIdNum.equals(other$authIdNum)) {
                    return false;
                }

                return true;
            }
        }
    }

    protected boolean canEqual(Object other) {
        return other instanceof SessionUser;
    }

    @Override
    public int hashCode() {
        int PRIME = 1;
        int result = 1;
        Object $id = this.getId();
        result = result * 59 + ($id == null ? 43 : $id.hashCode());
        Object $ossType = this.getOssType();
        result = result * 59 + ($ossType == null ? 43 : $ossType.hashCode());
        Object $orgId = this.getOrgId();
        result = result * 59 + ($orgId == null ? 43 : $orgId.hashCode());
        Object $loginName = this.getLoginName();
        result = result * 59 + ($loginName == null ? 43 : $loginName.hashCode());
        Object $name = this.getName();
        result = result * 59 + ($name == null ? 43 : $name.hashCode());
        Object $avator = this.getAvator();
        result = result * 59 + ($avator == null ? 43 : $avator.hashCode());
        Object $mobilePhone = this.getMobilePhone();
        result = result * 59 + ($mobilePhone == null ? 43 : $mobilePhone.hashCode());
        Object $telPhone = this.getTelPhone();
        result = result * 59 + ($telPhone == null ? 43 : $telPhone.hashCode());
        Object $email = this.getEmail();
        result = result * 59 + ($email == null ? 43 : $email.hashCode());
        Object $department = this.getDepartment();
        result = result * 59 + ($department == null ? 43 : $department.hashCode());
        Object $employeeNum = this.getEmployeeNum();
        result = result * 59 + ($employeeNum == null ? 43 : $employeeNum.hashCode());
        Object $sex = this.getSex();
        result = result * 59 + ($sex == null ? 43 : $sex.hashCode());
        Object $status = this.getStatus();
        result = result * 59 + ($status == null ? 43 : $status.hashCode());
        Object $description = this.getDescription();
        result = result * 59 + ($description == null ? 43 : $description.hashCode());
        Object $lastLoginTime = this.getLastLoginTime();
        result = result * 59 + ($lastLoginTime == null ? 43 : $lastLoginTime.hashCode());
        Object $lastLoginAddress = this.getLastLoginAddress();
        result = result * 59 + ($lastLoginAddress == null ? 43 : $lastLoginAddress.hashCode());
        Object $createTime = this.getCreateTime();
        result = result * 59 + ($createTime == null ? 43 : $createTime.hashCode());
        Object $updateTime = this.getUpdateTime();
        result = result * 59 + ($updateTime == null ? 43 : $updateTime.hashCode());
        Object $roles = this.getRoles();
        result = result * 59 + ($roles == null ? 43 : $roles.hashCode());
        Object $perms = this.getPerms();
        result = result * 59 + ($perms == null ? 43 : $perms.hashCode());
        Object $wechatOpenId = this.getWechatOpenId();
        result = result * 59 + ($wechatOpenId == null ? 43 : $wechatOpenId.hashCode());
        Object $wechatEpNum = this.getWechatEpNum();
        result = result * 59 + ($wechatEpNum == null ? 43 : $wechatEpNum.hashCode());
        Object $wechatNickName = this.getWechatNickName();
        result = result * 59 + ($wechatNickName == null ? 43 : $wechatNickName.hashCode());
        Object $wechatHeadImgUrl = this.getWechatHeadImgUrl();
        result = result * 59 + ($wechatHeadImgUrl == null ? 43 : $wechatHeadImgUrl.hashCode());
        Object $authName = this.getAuthName();
        result = result * 59 + ($authName == null ? 43 : $authName.hashCode());
        Object $authIdNum = this.getAuthIdNum();
        result = result * 59 + ($authIdNum == null ? 43 : $authIdNum.hashCode());
        return result;
    }

    @Override
    public String toString() {
        return "SessionUser(id=" + this.getId() + ", ossType=" + this.getOssType() + ", orgId=" + this.getOrgId() + ", loginName=" + this.getLoginName() + ", name=" + this.getName() + ", avator=" + this.getAvator() + ", mobilePhone=" + this.getMobilePhone() + ", telPhone=" + this.getTelPhone() + ", email=" + this.getEmail() + ", department=" + this.getDepartment() + ", employeeNum=" + this.getEmployeeNum() + ", sex=" + this.getSex() + ", status=" + this.getStatus() + ", description=" + this.getDescription() + ", lastLoginTime=" + this.getLastLoginTime() + ", lastLoginAddress=" + this.getLastLoginAddress() + ", createTime=" + this.getCreateTime() + ", updateTime=" + this.getUpdateTime() + ", roles=" + this.getRoles() + ", perms=" + this.getPerms() + ", wechatOpenId=" + this.getWechatOpenId() + ", wechatEpNum=" + this.getWechatEpNum() + ", wechatNickName=" + this.getWechatNickName() + ", wechatHeadImgUrl=" + this.getWechatHeadImgUrl() + ", authName=" + this.getAuthName() + ", authIdNum=" + this.getAuthIdNum() + ")";
    }
}

第四步 创建日志类

存储到数据库

@Value("${spring.application.name}")
private String applicationName; 服务名称,配置文件

@Pointcut("@annotation(com.jay.aoplog.web.annotation.LogOperation)") 日志注解位置

//登陆状态获取请求用户
// SessionUser sessionUser = SessionContext.getContext().getUser();
这里自己模拟一个new SessionUser()


/**
 * @description: 日志内容相关
 * @author: Jay
 * @create: 2021-10-12 10:42
 **/
@Aspect
@Component
@Slf4j
public class LogOperationAspect {

    @Autowired
    private AopUtilsDAO aopUtilsDAO;

    @Value("${spring.application.name}")
    private String applicationName;

    @Pointcut("@annotation(com.jay.aoplog.web.annotation.LogOperation)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //登陆状态获取请求用户
//        SessionUser  sessionUser = SessionContext.getContext().getUser();
        SessionUser  sessionUser = new SessionUser();
        sessionUser.setAuthName("jay");
        sessionUser.setId("9527");
        sessionUser.setAvator("touxiang");
        sessionUser.setAuthIdNum("827328399177732846");
        sessionUser.setDepartment("创新部门");
        sessionUser.setDescription("测试");
        sessionUser.setEmail("3123789712@qq.com");
        sessionUser.setEmployeeNum("9527");
        sessionUser.setLastLoginAddress("台湾,台北新竹市");
        sessionUser.setLoginName("登录人");
        sessionUser.setMobilePhone("18227311722");
        sessionUser.setOrgId("1");
        sessionUser.setOssType("1");
        sessionUser.setSex("男");
        sessionUser.setStatus("1");
        sessionUser.setWechatEpNum("1");
        sessionUser.setWechatHeadImgUrl("1");
        sessionUser.setWechatNickName("1");
        sessionUser.setWechatOpenId("1");
        //切面获取访问请求
        HttpServletRequest request = RequestUtils.getHttpServletRequest();

        try {
            //执行方法
            Object result = point.proceed();
            //执行时长(毫秒)
            long time = System.currentTimeMillis() - beginTime;
            saveLog(point, time,request, result,sessionUser);
            return result;
        }catch(DIYException e) {
            //执行时长(毫秒)
            long time = System.currentTimeMillis() - beginTime;
            //保存日志
            WebResult<Object> response = new WebResult<>();
            response.setCode(e.getCode());
            response.setMsg(e.getMsg());
            response.setData(e.getMessage());
            saveLog(point, time, request,e,sessionUser);
            return response;
        }
    }

    /**
     * 如果需要将日志存库,那么自己添加
     * @param joinPoint
     * @param time
     * @param result
     */
    private void saveLog(ProceedingJoinPoint joinPoint, long time,HttpServletRequest request, Object result,SessionUser user) {
        //获取注解对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogOperation annotation = method.getAnnotation(LogOperation.class);
        WebResult<Object> response = new WebResult<>();
        BeanUtils.copyProperties(result,response);
        AopUtilsPojo logInfo = new AopUtilsPojo();
        logInfo.setUserId(user!=null?Integer.valueOf(user.getId()):null);
        logInfo.setIp(RequestUtils.getIp(request));
        logInfo.setCreateTime(new Date());
        logInfo.setCreateBy(user!=null ? user.getName() : null);
        logInfo.setRequestUrl(request.getRequestURI());
        logInfo.setRequestDescription(annotation.description());
        logInfo.setName(user != null ? user.getName() : null);
        logInfo.setRequestMethod(request.getMethod());
        logInfo.setMobilePhone(user!=null?user.getMobilePhone():null);
        logInfo.setResponseMsg(response.getMsg());
        logInfo.setOrgId(user != null ?Long.valueOf(user.getOrgId()):null);
        logInfo.setApplicationName(applicationName);
        logInfo.setLogType(annotation.logType());
        //获取请求参数
        Object[] args = joinPoint.getArgs();
        ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
        String[] parameterNames = pnd.getParameterNames(method);
        String[] exclude = annotation.exclude();
        String  params = "";
        if (parameterNames!=null){
            Map<String, Object> paramMap = new HashMap<>(32);
            for (int i = 0; i < parameterNames.length; i++) {
                if (exclude.length == 0 || !ArrayUtils.contains(exclude,parameterNames[i])){
                    paramMap.put(parameterNames[i], args[i]);
                }
            }
            params = CommonUtil.getMapToString(paramMap);
        }
        logInfo.setRequestParam(params);
        aopUtilsDAO.insert(logInfo);
//        aopUtilsDao.insert(logInfo);
        if (user==null){
            //记录服务器日志 格式mart|{模块名称}|{请求类别}|{请求路径}|{请求时长}|{操作人}|{执行结果}
            log.info("mart|{}|{}|{}|{}|{}|{}",applicationName,annotation.logType(),request.getRequestURL().toString(),time,user,response.getMsg());
        }else {
            log.info("mart|{}|{}|{}|{}|{}|{}", applicationName, annotation.logType(), request.getRequestURL().toString(), time, user.getName() + user.getMobilePhone(), response.getMsg());
        }
    }


}

第五步 业务接口

@RestController
@Api(tags = "aop测试接口")
@RequestMapping("/log/api")

public class AopController {

    @Autowired
    private LogInfoService logInfoService;

    @PostMapping("/v1/save")
    @ApiOperation("aop保存")
    //注解实现
    @LogOperation(value = "日志value字段",logType = 1,description = "用户注册描述字段",exclude = "排除exclude字段")
    public WebResult<Object> saveAop(@RequestBody LogInfo logInfo){
        LogInfo register = logInfoService.register(logInfo);
        return new WebResult<>().ok(register);
    }
1接口请求数据

在这里插入图片描述

2控制台打印数据

在这里插入图片描述

3数据库数据存入

在这里插入图片描述

request_param内容
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值