【SpringBoot】+【Vue】集成AOP系统日志

新建logs表

【SpringBoot】+【Vue】集成AOP系统日志_第1张图片

添加aop依赖



   org.springframework.boot
   spring-boot-starter-aop

 新建获取ip地址工具类

import javax.servlet.http.HttpServletRequest;

/**
 * 功能:IpUtils
 * 获取ip地址工具类
 * 作者:爱因斯坦乐
 */
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;
    }

}

新建注解@HoneyLogs

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HoneyLogs {
    //操作的模块
    String operation();

    //操作类型
    LogType type();
}

新建枚举类

/**
 * 系统日志的操作类型的枚举
 */
public enum LogType {
    ADD("新增"), UPDATE("更新"), DELETE("删除"), LOGIN("登录");
    private String value;

    public String getValue() {
        return value;
    }

    LogType(String value) {
        this.value = value;
    }
}

 创建日志实体类

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 功能:Logs
 * 日志实体类
 * 作者:爱因斯坦乐
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Logs {
    @TableId(type = IdType.AUTO)
    private Integer id;
    private String operation;
    private String type;
    private String ip;
    private String user;
    private String time;
}

 LogsMapper

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.shieldspring.entity.Logs;

public interface LogsMapper extends BaseMapper {
}

LogsService

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.shieldspring.entity.Logs;
import com.example.shieldspring.mapper.LogsMapper;
import org.springframework.stereotype.Service;

/**
 * 功能:LogsService
 * 作者:爱因斯坦乐
 */
@Service
public class LogsService extends ServiceImpl {
}

Logs接口

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.shieldspring.common.Result;
import com.example.shieldspring.entity.Logs;
import com.example.shieldspring.service.LogsService;
import com.example.shieldspring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 功能:LogsController
 * 作者:爱因斯坦乐
 * 日期:2024/6/30
 */
@RestController
@RequestMapping("/logs")
public class LogsController {
    @Autowired
    LogsService logsService;
    @Autowired
    UserService userService;

    //    删除
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        logsService.removeById(id);
        return Result.success();
    }

    //    批量删除
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List ids) {
        logsService.removeBatchByIds(ids);
        return Result.success();
    }

    //查询全部信息
    @GetMapping("/selectAll")
    public Result selectAll() {
        List logsList = logsService.list(new QueryWrapper().orderByDesc("id"));
        return Result.success(logsList);
    }

    //分页查询
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String operation) {
        QueryWrapper queryWrapper = new QueryWrapper().orderByDesc("id");
        queryWrapper.like(StrUtil.isNotBlank(operation), "operation", operation);
        Page page = logsService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }
}

切面LogsAspect

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import com.example.shieldspring.common.HoneyLogs;
import com.example.shieldspring.entity.Login;
import com.example.shieldspring.entity.Logs;
import com.example.shieldspring.service.LogsService;
import com.example.shieldspring.utils.IpUtils;
import com.example.shieldspring.utils.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.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 功能:LogsAspect
 * 切面
 * 作者:爱因斯坦乐
 * 日期:2024/6/30
 */
@Component
@Aspect
@Slf4j
public class LogsAspect {
    @Resource
    LogsService logsService;

    @AfterReturning(pointcut = "@annotation(honeyLogs)", returning = "jsonResult")
    public void recordLog(JoinPoint joinPoint, HoneyLogs honeyLogs, Object jsonResult) {
        //获取当前登陆的用户信息
        Login login = TokenUtils.getCurrentLogin();
        if (login == null) {
            //null时从参数里获取登录信息  登录
            Object[] args = joinPoint.getArgs();
            if (ArrayUtil.isNotEmpty(args)) {
                if (args[0] instanceof Login) {
                    login = (Login) args[0];
                }
            }
        }
        if (login == null) {
            log.error("记录日志报错,为获取到当前操作用户信息");
            return;
        }
        //获取HttpServletRequest对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest requset = servletRequestAttributes.getRequest();
        //获取IP信息
        String ipAddr = IpUtils.getIpAddr(requset);
        //组装日志的实体对象
        Logs logs = Logs.builder().user(login.getName()).operation(honeyLogs.operation())
                .type(honeyLogs.type().getValue()).ip(ipAddr).time(DateUtil.now()).build();
        //插入数据库
        ThreadUtil.execAsync(() -> {
            try {
                logsService.save(logs);
            }catch (Exception e){
                log.error("存日志失败");
            }
        });
    }
}

前端实现logs.vue



你可能感兴趣的:(spring,vue.js,java,aop,交互)