新增:个人中心新增查询操作日志功能,优化日志表结构,并支持关闭记录内网 IP 操作

This commit is contained in:
2023-01-16 00:18:53 +08:00
parent 79c741b68e
commit f4ea2d44d6
36 changed files with 1272 additions and 119 deletions

View File

@@ -32,10 +32,10 @@ limitations under the License.
<description>系统监控模块(存放系统监控模块相关功能,例如:日志管理、服务监控等)</description>
<dependencies>
<!-- 公共模块(存放公共工具类,公共配置等) -->
<!-- 系统管理模块(存放系统管理模块相关功能,例如:部门管理、角色管理、用户管理等) -->
<dependency>
<groupId>top.charles7c</groupId>
<artifactId>continew-admin-common</artifactId>
<artifactId>continew-admin-system</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -19,7 +19,7 @@ package top.charles7c.cnadmin.monitor.annotation;
import java.lang.annotation.*;
/**
* 操作日志注解(用于接口方法或类上)
* 系统日志注解(用于接口方法或类上)
*
* @author Charles7c
* @since 2022/12/23 20:00
@@ -30,7 +30,7 @@ import java.lang.annotation.*;
public @interface Log {
/**
* 操作日志描述
* 日志描述
*/
String value() default "";

View File

@@ -25,28 +25,33 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 操作日志配置属性
* 系统日志配置属性
*
* @author Charles7c
* @since 2022/12/24 23:04
*/
@Data
@Component
@ConfigurationProperties(prefix = "logging.operation")
@ConfigurationProperties(prefix = "logging.system")
public class LogProperties {
/**
* 是否启用操作日志
* 是否启用系统日志
*/
private Boolean enabled = false;
private Boolean enabled;
/**
* 是否记录内网 IP 操作
*/
private Boolean includeInnerIp;
/**
* 哪些请求方式不记录系统日志
*/
private List<String> excludeMethods = new ArrayList<>();
/**
* 脱敏字段
*/
private List<String> desensitize = new ArrayList<>();
/**
* 不记录操作日志的请求方式
*/
private List<String> excludeMethods = new ArrayList<>();
}

View File

@@ -19,22 +19,24 @@ package top.charles7c.cnadmin.monitor.enums;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.annotation.IEnum;
/**
* 操作日志级别枚举
* 操作结果枚举
*
* @author Charles7c
* @since 2022/12/25 9:09
*/
@Getter
@RequiredArgsConstructor
public enum LogLevelEnum {
public enum LogResultEnum implements IEnum<Integer> {
/** 普通 */
INFO("普通"),
/** 成功 */
SUCCESS(1, "成功"),
/** 错误 */
ERROR("错误"),;
/** 失败 */
FAILURE(2, "失败"),;
/** 描述 */
private final Integer value;
private final String description;
}

View File

@@ -42,20 +42,21 @@ import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import top.charles7c.cnadmin.common.model.dto.OperationLog;
import top.charles7c.cnadmin.common.model.dto.LogContext;
import top.charles7c.cnadmin.common.util.IpUtils;
import top.charles7c.cnadmin.common.util.ServletUtils;
import top.charles7c.cnadmin.common.util.helper.LoginHelper;
import top.charles7c.cnadmin.common.util.holder.LogContextHolder;
import top.charles7c.cnadmin.monitor.annotation.Log;
import top.charles7c.cnadmin.monitor.config.properties.LogProperties;
import top.charles7c.cnadmin.monitor.enums.LogLevelEnum;
import top.charles7c.cnadmin.monitor.enums.LogResultEnum;
import top.charles7c.cnadmin.monitor.model.entity.SysLog;
/**
* 操作日志拦截器
* 系统日志拦截器
*
* @author Charles7c
* @since 2022/12/24 21:14
@@ -87,14 +88,14 @@ public class LogInterceptor implements HandlerInterceptor {
return;
}
// 记录描述
// 记录日志描述
this.logDescription(sysLog, handler);
// 记录请求信息
this.logRequest(sysLog, request);
// 记录响应信息
this.logResponse(sysLog, response);
// 保存操作日志
// 保存系统日志
SpringUtil.getApplicationContext().publishEvent(sysLog);
}
@@ -102,31 +103,31 @@ public class LogInterceptor implements HandlerInterceptor {
* 记录操作时间
*/
private void logCreateTime() {
OperationLog operationLog = new OperationLog();
operationLog.setCreateUser(LoginHelper.getUserId());
operationLog.setCreateTime(LocalDateTime.now());
LogContextHolder.set(operationLog);
LogContext logContext = new LogContext();
logContext.setCreateUser(LoginHelper.getUserId());
logContext.setCreateTime(LocalDateTime.now());
LogContextHolder.set(logContext);
}
/**
* 记录请求耗时及异常信息
*
* @return 日志信息
* @return 系统日志信息
*/
private SysLog logElapsedTimeAndException() {
OperationLog operationLog = LogContextHolder.get();
if (operationLog != null) {
LogContext logContext = LogContextHolder.get();
if (logContext != null) {
LogContextHolder.remove();
SysLog sysLog = new SysLog();
sysLog.setCreateTime(operationLog.getCreateTime());
sysLog.setCreateTime(logContext.getCreateTime());
sysLog.setElapsedTime(System.currentTimeMillis() - LocalDateTimeUtil.toEpochMilli(sysLog.getCreateTime()));
sysLog.setLogLevel(LogLevelEnum.INFO);
sysLog.setResult(LogResultEnum.SUCCESS);
// 记录异常信息
Exception exception = operationLog.getException();
Exception exception = logContext.getException();
if (exception != null) {
sysLog.setLogLevel(LogLevelEnum.ERROR);
sysLog.setException(ExceptionUtil.stacktraceToString(operationLog.getException(), -1));
sysLog.setResult(LogResultEnum.FAILURE);
sysLog.setException(ExceptionUtil.stacktraceToString(exception, -1));
}
return sysLog;
}
@@ -137,7 +138,7 @@ public class LogInterceptor implements HandlerInterceptor {
* 记录日志描述
*
* @param sysLog
* 日志信息
* 系统日志信息
* @param handler
* 处理器
*/
@@ -148,7 +149,7 @@ public class LogInterceptor implements HandlerInterceptor {
if (methodOperation != null) {
sysLog.setDescription(
StrUtil.isNotBlank(methodOperation.summary()) ? methodOperation.summary() : "请在该接口方法上指定操作日志描述");
StrUtil.isNotBlank(methodOperation.summary()) ? methodOperation.summary() : "请在该接口方法上指定日志描述");
}
// 例如:@Log("获取验证码") -> 获取验证码
if (methodLog != null && StrUtil.isNotBlank(methodLog.value())) {
@@ -160,7 +161,7 @@ public class LogInterceptor implements HandlerInterceptor {
* 记录请求信息
*
* @param sysLog
* 日志信息
* 系统日志信息
* @param request
* 请求对象
*/
@@ -184,18 +185,21 @@ public class LogInterceptor implements HandlerInterceptor {
* 记录响应信息
*
* @param sysLog
* 日志信息
* 系统日志信息
* @param response
* 响应对象
*/
private void logResponse(SysLog sysLog, HttpServletResponse response) {
sysLog.setStatusCode(response.getStatus());
int status = response.getStatus();
sysLog.setStatusCode(status);
sysLog.setResponseHeader(this.desensitize(ServletUtil.getHeadersMap(response)));
// 响应体(不记录非 JSON 响应数据)
String responseBody = this.getResponseBody(response);
if (StrUtil.isNotBlank(responseBody) && JSONUtil.isTypeJSON(responseBody)) {
sysLog.setResponseBody(responseBody);
}
// 操作失败:>= 400
sysLog.setResult(status >= HttpStatus.HTTP_BAD_REQUEST ? LogResultEnum.FAILURE : sysLog.getResult());
}
/**
@@ -258,7 +262,7 @@ public class LogInterceptor implements HandlerInterceptor {
}
/**
* 检查是否要记录操作日志
* 检查是否要记录系统日志
*
* @param handler
* /
@@ -267,28 +271,34 @@ public class LogInterceptor implements HandlerInterceptor {
* @return true 需要记录false 不需要记录
*/
private boolean checkIsNeedRecord(Object handler, HttpServletRequest request) {
// 1、未启用时不需要记录操作日志
// 1、未启用时不需要记录系统日志
if (!(handler instanceof HandlerMethod) || Boolean.FALSE.equals(operationLogProperties.getEnabled())) {
return false;
}
// 2、排除不需要记录日志的接口
// 2、检查是否需要记录内网 IP 操作
boolean isInnerIp = IpUtils.isInnerIP(ServletUtil.getClientIP(request));
if (isInnerIp && Boolean.FALSE.equals(operationLogProperties.getIncludeInnerIp())) {
return false;
}
// 3、排除不需要记录系统日志的接口
HandlerMethod handlerMethod = (HandlerMethod)handler;
Log methodLog = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Log.class);
// 2.1 请求方式不要求记录且请求上没有 @Log 注解,则不记录操作日志
// 3.1 请求方式不要求记录且请求上没有 @Log 注解,则不记录系统日志
if (operationLogProperties.getExcludeMethods().contains(request.getMethod()) && methodLog == null) {
return false;
}
// 2.2 如果接口上既没有 @Log 注解,也没有 @Operation 注解,则不记录操作日志
// 3.2 如果接口上既没有 @Log 注解,也没有 @Operation 注解,则不记录系统日志
Operation methodOperation = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Operation.class);
if (methodLog == null && methodOperation == null) {
return false;
}
// 2.3 如果接口被隐藏,不记录操作日志
// 3.3 如果接口被隐藏,不记录系统日志
if (methodOperation != null && methodOperation.hidden()) {
return false;
}
// 2.4 如果接口上有 @Log 注解,但是要求忽略该接口,则不记录操作日志
// 3.4 如果接口上有 @Log 注解,但是要求忽略该接口,则不记录系统日志
return methodLog == null || !methodLog.ignore();
}
}

View File

@@ -21,7 +21,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import top.charles7c.cnadmin.monitor.model.entity.SysLog;
/**
* 操作日志 Mapper
* 系统日志 Mapper
*
* @author Charles7c
* @since 2022/12/22 21:47

View File

@@ -24,10 +24,10 @@ import lombok.Data;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import top.charles7c.cnadmin.monitor.enums.LogLevelEnum;
import top.charles7c.cnadmin.monitor.enums.LogResultEnum;
/**
* 操作日志实体
* 系统日志实体
*
* @author Charles7c
* @since 2022/12/25 9:11
@@ -44,18 +44,13 @@ public class SysLog implements Serializable {
@TableId
private Long logId;
/**
* 日志级别
*/
private LogLevelEnum logLevel;
/**
* 日志描述
*/
private String description;
/**
* 请求 URL
* 请求URL
*/
private String requestUrl;
@@ -95,12 +90,17 @@ public class SysLog implements Serializable {
private Long elapsedTime;
/**
* 请求IP
* 操作结果1成功 2失败
*/
private LogResultEnum result;
/**
* 操作IP
*/
private String requestIp;
/**
* 操作地
* 操作地
*/
private String location;

View File

@@ -0,0 +1,50 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.cnadmin.monitor.model.query;
import static top.charles7c.cnadmin.common.annotation.Query.Type;
import java.io.Serializable;
import lombok.Data;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springdoc.api.annotations.ParameterObject;
import top.charles7c.cnadmin.common.annotation.Query;
/**
* 操作日志查询条件
*
* @author Charles7c
* @since 2023/1/15 11:43
*/
@Data
@ParameterObject
@Schema(description = "操作日志查询条件")
public class OperationLogQuery implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 操作人
*/
@Schema(description = "操作人")
@Query(property = "createUser", type = Type.EQUAL)
private Long uid;
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.cnadmin.monitor.model.vo;
import java.io.Serializable;
import java.time.LocalDateTime;
import lombok.Data;
import io.swagger.v3.oas.annotations.media.Schema;
import com.fasterxml.jackson.annotation.JsonIgnore;
import top.charles7c.cnadmin.monitor.enums.LogResultEnum;
/**
* 操作日志信息
*
* @author Charles7c
* @since 2023/1/14 18:27
*/
@Data
@Schema(description = "操作日志信息")
public class OperationLogVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 日志ID
*/
@Schema(description = "日志ID")
private Long logId;
/**
* 操作内容
*/
@Schema(description = "操作内容")
private String description;
/**
* 操作结果1成功 2失败
*/
@Schema(description = "操作结果1成功 2失败", type = "Integer", allowableValues = {"1", "2"})
private LogResultEnum result;
/**
* 操作IP
*/
@Schema(description = "操作IP")
private String requestIp;
/**
* 操作地点
*/
@Schema(description = "操作地点")
private String location;
/**
* 浏览器
*/
@Schema(description = "浏览器")
private String browser;
/**
* 操作人
*/
@JsonIgnore
private Long createUser;
/**
* 操作人
*/
@Schema(description = "操作人")
private String createUserString;
/**
* 操作时间
*/
@Schema(description = "操作时间")
private LocalDateTime createTime;
}

View File

@@ -17,7 +17,7 @@
package top.charles7c.cnadmin.monitor.service;
/**
* 操作日志业务接口
* 系统日志业务接口
*
* @author Charles7c
* @since 2022/12/23 20:12

View File

@@ -0,0 +1,42 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.cnadmin.monitor.service;
import top.charles7c.cnadmin.common.model.query.PageQuery;
import top.charles7c.cnadmin.common.model.vo.PageInfo;
import top.charles7c.cnadmin.monitor.model.query.OperationLogQuery;
import top.charles7c.cnadmin.monitor.model.vo.OperationLogVO;
/**
* 操作日志业务接口
*
* @author Charles7c
* @since 2023/1/15 21:05
*/
public interface OperationLogService {
/**
* 分页查询列表
*
* @param query
* 查询条件
* @param pageQuery
* 分页查询条件
* @return 分页信息
*/
PageInfo<OperationLogVO> list(OperationLogQuery query, PageQuery pageQuery);
}

View File

@@ -28,7 +28,7 @@ import top.charles7c.cnadmin.monitor.model.entity.SysLog;
import top.charles7c.cnadmin.monitor.service.LogService;
/**
* 操作日志业务实现类
* 系统日志业务实现类
*
* @author Charles7c
* @since 2022/12/23 20:12

View File

@@ -0,0 +1,90 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.cnadmin.monitor.service.impl;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import cn.hutool.core.util.StrUtil;
import top.charles7c.cnadmin.common.model.query.PageQuery;
import top.charles7c.cnadmin.common.model.vo.PageInfo;
import top.charles7c.cnadmin.common.util.ReflectUtils;
import top.charles7c.cnadmin.common.util.helper.QueryHelper;
import top.charles7c.cnadmin.monitor.mapper.LogMapper;
import top.charles7c.cnadmin.monitor.model.entity.SysLog;
import top.charles7c.cnadmin.monitor.model.query.OperationLogQuery;
import top.charles7c.cnadmin.monitor.model.vo.OperationLogVO;
import top.charles7c.cnadmin.monitor.service.OperationLogService;
import top.charles7c.cnadmin.system.mapper.UserMapper;
import top.charles7c.cnadmin.system.model.entity.SysUser;
/**
* 操作日志业务实现类
*
* @author Charles7c
* @since 2023/1/15 21:05
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class OperationLogServiceImpl implements OperationLogService {
private final LogMapper logMapper;
private final UserMapper userMapper;
@Override
public PageInfo<OperationLogVO> list(OperationLogQuery query, PageQuery pageQuery) {
QueryWrapper<SysLog> queryWrapper = QueryHelper.build(query);
// 限定查询信息
String[] fieldsName = ReflectUtils.getNonStaticFieldsName(OperationLogVO.class);
List<String> columns = Arrays.stream(fieldsName).map(StrUtil::toUnderlineCase)
.filter(n -> !n.endsWith("string")).collect(Collectors.toList());
queryWrapper.select(columns);
// 分页查询
IPage<SysLog> page = logMapper.selectPage(pageQuery.toPage(), queryWrapper);
PageInfo<OperationLogVO> pageInfo = PageInfo.build(page, OperationLogVO.class);
pageInfo.getList().forEach(this::fill);
return pageInfo;
}
/**
* 填充数据
*
* @param vo
* VO
*/
private void fill(OperationLogVO vo) {
Long createUser = vo.getCreateUser();
if (createUser == null) {
return;
}
SysUser sysUser = userMapper.selectById(createUser);
vo.setCreateUserString(sysUser.getNickname());
}
}