新建logs表
添加aop依赖
<!-- aop依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
新建获取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<Logs> {
}
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<LogsMapper, Logs> {
}
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<Integer> ids) {
logsService.removeBatchByIds(ids);
return Result.success();
}
//查询全部信息
@GetMapping("/selectAll")
public Result selectAll() {
List<Logs> logsList = logsService.list(new QueryWrapper<Logs>().orderByDesc("id"));
return Result.success(logsList);
}
//分页查询
@GetMapping("/selectByPage")
public Result selectByPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String operation) {
QueryWrapper<Logs> queryWrapper = new QueryWrapper<Logs>().orderByDesc("id");
queryWrapper.like(StrUtil.isNotBlank(operation), "operation", operation);
Page<Logs> 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
<template>
<div>
<div>
<!-- 查询条件 -->
<el-input style="margin-right: 40px;width:200px" placeholder="查询标题" v-model="operation"></el-input>
<el-button type="primary" @click="load(1)">查询</el-button>
<el-button @click="reset" style="margin-right: 40px;">重置</el-button>
</div>
<!-- 操作 -->
<div style="margin: 10px 0;">
<el-button type="danger" plain @click="delBatch">批量删除</el-button>
</div>
<el-table
:data="logs"
:header-cell-style="{backgroundColor:'aliceblue',color:'#666'}"
@selection-change="handleSelectionChange"
>
<el-table-column type="selection" width="55" align="center"></el-table-column>
<el-table-column prop="id" label="序号"></el-table-column>
<el-table-column prop="operation" label="操作模块"></el-table-column>
<el-table-column prop="type" label="操作类型">
<template v-slot="scope">
<el-tag type="primary" v-if="scope.row.type==='新增'">{{scope.row.type}}</el-tag>
<el-tag type="info" v-if="scope.row.type==='更新'">{{scope.row.type}}</el-tag>
<el-tag type="danger" v-if="scope.row.type==='删除'">{{scope.row.type}}</el-tag>
<el-tag type="danger" v-if="scope.row.type==='批量删除'">{{scope.row.type}}</el-tag>
<el-tag type="success" v-if="scope.row.type==='登录'">{{scope.row.type}}</el-tag>
<el-tag type="success" v-if="scope.row.type==='导出'">{{scope.row.type}}</el-tag>
<el-tag type="success" v-if="scope.row.type==='导入'">{{scope.row.type}}</el-tag>
</template>
</el-table-column>
<el-table-column prop="ip" label="操作人IP" align="center"></el-table-column>
<el-table-column prop="user" label="操作人" align="center"></el-table-column>
<el-table-column prop="time" label="发布时间" align="center"></el-table-column>
<el-table-column label="操作" align="center" width="200px" fixed="right">
<template v-slot="scope" width="180">
<el-button size="mini" type="danger" plain @click="del(scope.row.id)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页 -->
<div style="margin: 10px 0;">
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="pageNum"
:page-sizes="[5, 10, 15, 20]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total"
align="center"
></el-pagination>
</div>
</div>
</template>
<script>
export default {
data () {
return {
isSwitchClicked: false,
logs: [],
pageNum: 1,//当前页码
pageSize: 5,//每页个数
operation: '',
total: 0,
FormVisible: false,
form: {},//新增表单数据
user: JSON.parse(localStorage.getItem('hon-admin') || '{}'),
ids: []
}
},
created () { this.load() },
methods: {
//分页查询
load (pageNum) {
if (pageNum) {
this.pageNum = pageNum
}
this.$request.get('/logs/selectByPage', {
params: {
pageNum: this.pageNum,
pageSize: this.pageSize,
operation: this.operation,
}
}).then(res => {
this.logs = res.date.records
// console.log(this.spys)
this.total = res.date.total
})
},
// 分页方法
handleSizeChange (pageSize) {
this.pageSize = pageSize
this.load()
},
handleCurrentChange (pageNum) {
this.load(pageNum)
},
//重置
reset () {
this.operation = ''
this.load()
},
//删除按钮
del (id) {
this.isSwitchClicked = true
this.$confirm('您确认删除吗?', '确认删除', { type: "warning" }).then(response => {
this.$request.delete('logs/delete/' + id).then(res => {
if (res.code === '200') {
this.$message.success('删除成功')
this.load(1)
} else {
this.$message.error(res.msg)
}
})
}).catch(() => {
// 用户点击了取消按钮,什么也不做
})
},
//批量删除
delBatch () {
if (!this.ids.length) {
this.$message.warning('请选择数据')
return
}
this.$confirm('您确认批量删除这些数据吗?', '确认删除', { type: "warning" }).then(response => {
this.$request.delete('logs/delete/batch', { data: this.ids }).then(res => {
if (res.code === '200') {
this.$message.success('删除成功')
this.load(1)
} else {
this.$message.error(res.msg)
}
})
}).catch(() => {
// 用户点击了取消按钮,什么也不做
})
},
handleSelectionChange (rows) {
this.ids = rows.map(v => v.id)
}
}
}
</script>
<style>
.el-tooltip__popper {
max-width: 400px !important;
}
</style>