使用aop实现日志记录

1.添加pom依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2.添加获取IP地址工具类

import javax.servlet.http.HttpServletRequest;

public class IpUtils {

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

}

3.自定义实现记录的注解

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLogs {
    //操作名称
    String operation();
    //操作类型
    String type();
}

4.添加LogsAspect 类

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import com.mai.dao.LogsMapper;
import com.mai.entity.Logs;
import com.mai.entity.User;
import com.mai.config.SysLogs;
import com.mai.util.IpUtils;
import com.mai.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
@Slf4j
public class LogsAspect {

    @Autowired
    private LogsMapper logsMapper;

    @AfterReturning(pointcut = "@annotation(sysLogs)",returning = "jsonResult")
    public void recordLog(JoinPoint joinPoint, SysLogs sysLogs,Object jsonResult){
        // 获取当前登录的用户的信息
        User loginUser = TokenUtils.getCurrentUser();
        if (loginUser == null) { // 用户未登录的情况下  loginUser是null  是null的话我们就要从参数里面获取操作人信息
            // 登录、注册
            Object[] args = joinPoint.getArgs();
            if (ArrayUtil.isNotEmpty(args)) {
                if (args[0] instanceof User) {
                    loginUser = (User) args[0];
                }
            }
        }
        if (loginUser == null) {
            log.error("记录日志信息报错,未获取到当前操作用户信息");
            return;
        }

        // 获取HttpServletRequest对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        String ipAddr = IpUtils.getIpAddr(request);
        Logs logs = Logs.builder()
                .ip(ipAddr)
                .operation(sysLogs.operation())
                .type(sysLogs.type())
                .time(DateUtil.now())
                .user(loginUser.getUsername())
                .build();

        ThreadUtil.execAsync(()->{
            // 异步记录日志信息
            logsMapper.insert(logs);
        });

    }
}

注意:@AfterReturning(pointcut = "@annotation(sysLogs)",returning = "jsonResult")中的sysLogs开头小写

5.使用例子

@SysLogs(operation = "公告信息",type = "删除")
    @ApiOperation("批量删除")
    @DeleteMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        noticeService.deleteBatch(ids);
        return Result.success();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值