日志相关

This commit is contained in:
caozehui
2025-02-12 14:44:29 +08:00
parent aca953e827
commit 04135f7044
13 changed files with 191 additions and 34 deletions

View File

@@ -17,6 +17,7 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@@ -45,6 +46,7 @@ public class PqIcdPathServiceImpl extends ServiceImpl<PqIcdPathMapper, PqIcdPath
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean addIcd(PqIcdPathParam param) {
this.checkRepeat(param, false);
PqIcdPath pqIcdPath = new PqIcdPath();
@@ -54,6 +56,7 @@ public class PqIcdPathServiceImpl extends ServiceImpl<PqIcdPathMapper, PqIcdPath
}
@Override
@Transactional(rollbackFor = {Exception.class})
public boolean updateIcd(PqIcdPathParam.UpdateParam param) {
this.checkRepeat(param, true);
PqIcdPath pqIcdPath = new PqIcdPath();
@@ -62,6 +65,7 @@ public class PqIcdPathServiceImpl extends ServiceImpl<PqIcdPathMapper, PqIcdPath
}
@Override
@Transactional(rollbackFor = {Exception.class})
public boolean deleteIcd(List<String> ids) {
return this.lambdaUpdate().in(PqIcdPath::getId, ids).set(PqIcdPath::getState, DataStateEnum.DELETED.getCode()).update();
}

View File

@@ -14,6 +14,7 @@ import com.njcn.gather.type.pojo.po.DevType;
import com.njcn.gather.type.service.IDevTypeService;
import com.njcn.web.factory.PageFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@@ -62,6 +63,7 @@ public class DevTypeServiceImpl extends ServiceImpl<DevTypeMapper, DevType> impl
}
@Override
@Transactional(rollbackFor = {Exception.class})
public boolean addDevType(DevTypeParam addParam) {
this.checkRepeat(addParam, false);
DevType devType = new DevType();
@@ -71,6 +73,7 @@ public class DevTypeServiceImpl extends ServiceImpl<DevTypeMapper, DevType> impl
}
@Override
@Transactional(rollbackFor = {Exception.class})
public boolean updateDevType(DevTypeParam.UpdateParam updateParam) {
this.checkRepeat(updateParam, true);
DevType devType = new DevType();
@@ -79,6 +82,7 @@ public class DevTypeServiceImpl extends ServiceImpl<DevTypeMapper, DevType> impl
}
@Override
@Transactional(rollbackFor = {Exception.class})
public boolean deleteDevType(List<String> ids) {
return this.lambdaUpdate().in(DevType::getId, ids).set(DevType::getState, DataStateEnum.DELETED.getCode()).update();
}

View File

@@ -4,11 +4,13 @@ import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Slf4j
@MapperScan("com.njcn.**.mapper")
@SpringBootApplication(scanBasePackages = "com.njcn")
//@EnableAspectJAutoProxy
public class EntranceApplication {
public static void main(String[] args) {

View File

@@ -33,12 +33,6 @@
<artifactId>user</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>

View File

@@ -14,12 +14,16 @@ import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.JwtUtil;
import com.njcn.common.utils.LogUtil;
import com.njcn.gather.system.auth.pojo.Token;
import com.njcn.gather.system.log.pojo.enums.LogOperationTypeEnum;
import com.njcn.gather.system.log.pojo.po.SysLogAudit;
import com.njcn.gather.system.log.service.ISysLogAuditService;
import com.njcn.gather.user.pojo.constant.UserValidMessage;
import com.njcn.gather.user.user.pojo.param.SysUserParam;
import com.njcn.gather.user.user.pojo.po.SysUser;
import com.njcn.gather.user.user.service.ISysUserService;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.HttpResultUtil;
import com.njcn.web.utils.HttpServletUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
@@ -28,6 +32,8 @@ import org.apache.logging.log4j.util.Strings;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
@@ -40,6 +46,7 @@ import java.util.Map;
public class AuthController extends BaseController {
private final ISysUserService sysUserService;
private final ISysLogAuditService sysLogAuditService;
// @RequestMapping("/login")
// public HttpResult<Token> login() {
@@ -86,6 +93,7 @@ public class AuthController extends BaseController {
customCacheUtil.putWithExpireTime(accessToken, JSON.toJSONString(user), DateUnit.DAY.getMillis() * 2);
customCacheUtil.putWithExpireTime(refreshToken, JSON.toJSONString(user), (DateUnit.DAY.getMillis() * 4));
sysLogAuditService.saveAuthLog(user.getName(), 1);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, token, methodDescribe);
}
}
@@ -105,6 +113,10 @@ public class AuthController extends BaseController {
customCacheUtil.remove(accessToken);
customCacheUtil.remove(refreshToken);
Map<String, Object> map = JwtUtil.parseToken(accessToken);
SysUser user = sysUserService.getById((String) map.get(SecurityConstants.USER_ID));
sysLogAuditService.saveAuthLog(user.getName(), 2);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, null, methodDescribe);
}
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe);
@@ -140,4 +152,6 @@ public class AuthController extends BaseController {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, null, methodDescribe);
}
}
}

View File

@@ -1,5 +1,6 @@
package com.njcn.gather.system.log.aop;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
@@ -7,14 +8,19 @@ import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.njcn.common.bean.CustomCacheUtil;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.SecurityConstants;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.JwtUtil;
import com.njcn.db.mybatisplus.constant.UserConstant;
import com.njcn.gather.system.log.pojo.enums.LogLevelEnum;
import com.njcn.gather.system.log.pojo.enums.LogOperationTypeEnum;
import com.njcn.gather.system.log.pojo.enums.LogResponseEnum;
import com.njcn.gather.system.log.pojo.po.SysLogAudit;
import com.njcn.gather.system.log.service.ISysLogAuditService;
import com.njcn.gather.user.user.pojo.po.SysUser;
import com.njcn.gather.user.user.service.ISysUserService;
import com.njcn.web.utils.HttpServletUtil;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
@@ -27,6 +33,9 @@ import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.*;
/**
@@ -36,15 +45,16 @@ import java.util.concurrent.*;
@Aspect
@Component
@Slf4j
@RequiredArgsConstructor
public class LogAdvice implements ApplicationListener<ContextRefreshedEvent> {
private final ISysLogAuditService sysLogAuditService;
private final ISysUserService sysUserService;
private BlockingQueue<SysLogAudit> logQueue = new LinkedBlockingDeque<>();
@Pointcut(value = "execution(* com.njcn.gather..controller.*(..))")
// @Pointcut(value = "execution(* com.njcn.gather..controller.*(..))")
@Pointcut(value = "execution(* com.njcn.gather..controller.*.*(..)) && !execution(* com.njcn.gather..controller.AuthController.*(..))")
public void logPointcut() {
}
@@ -55,49 +65,52 @@ public class LogAdvice implements ApplicationListener<ContextRefreshedEvent> {
String authorization = request.getHeader(SecurityConstants.AUTHORIZATION_KEY);
if (StrUtil.isNotBlank(authorization)) {
String tokenStr = authorization.replace(SecurityConstants.AUTHORIZATION_PREFIX, Strings.EMPTY);
CustomCacheUtil customCacheUtil = SpringUtil.getBean(CustomCacheUtil.CACHE_NAME);
String userjson = customCacheUtil.get(tokenStr, false);
SysUser user = JSONObject.parseObject(userjson, SysUser.class);
username = user.getName();
}
// CustomCacheUtil customCacheUtil = SpringUtil.getBean(CustomCacheUtil.CACHE_NAME);
// String userjson = customCacheUtil.get(tokenStr, false);
// SysUser user = JSONObject.parseObject(userjson, SysUser.class);
// username = user.getName();
// String operationType = "";
// String operateResult = "成功";
// Integer level = 0;
// Integer warn = 0;
Map<String, Object> map = JwtUtil.parseToken(tokenStr);
SysUser user = sysUserService.getById((String) map.get(SecurityConstants.USER_ID));
if(ObjectUtil.isNotNull(user)){
username = user.getName();
}
}
Object result = null;
try {
result = joinPoint.proceed();
addLogToQueue(joinPoint, "".equals(username) ? UserConstant.UNKNOWN_USER_ID : username, "操作日志", "成功", 0, 0);
addLogToQueue(joinPoint, "".equals(username) ? UserConstant.UNKNOWN_USER_ID : username, LogOperationTypeEnum.OPERATE.getMsg(), 1, LogLevelEnum.INFO.getCode(), 0);
} catch (Throwable e) {
addLogToQueue(joinPoint, "".equals(username) ? UserConstant.UNKNOWN_USER_ID : username, "告警日志", "失败", 1, 1);
addLogToQueue(joinPoint, "".equals(username) ? UserConstant.UNKNOWN_USER_ID : username, LogOperationTypeEnum.OPERATE.getMsg(), 0, LogLevelEnum.ERROR.getCode(), 1);
throw e;
}
return result;
}
private void addLogToQueue(ProceedingJoinPoint joinPoint, String username, String operationType, String result, Integer level, Integer warn) {
private void addLogToQueue(ProceedingJoinPoint joinPoint, String username, String operationType, Integer result, Integer level, Integer warn) {
SysLogAudit sysLogAudit = new SysLogAudit();
sysLogAudit.setCreateBy(username);
sysLogAudit.setOperateType(operationType);
sysLogAudit.setLevel(level);
sysLogAudit.setWarn(warn);
sysLogAudit.setWarn(warn); //0-未告警1-告警
sysLogAudit.setCreateBy(username);
HttpServletRequest request = HttpServletUtil.getRequest();
sysLogAudit.setIp(request.getRemoteAddr());
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
OperateInfo operateInfo = method.getAnnotation(OperateInfo.class);
ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
String resultStr = (result == 1 ? "成功" : "失败");
if (operateInfo != null) {
//注解上的操作类型
sysLogAudit.setResult(operateInfo.operateType() + result);
sysLogAudit.setResult(operateInfo.operateType() + resultStr);
}
if (apiOperation != null) {
//注解上的描述
sysLogAudit.setRemark(apiOperation.value());
String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
sysLogAudit.setRemark(username + "用户:" + now + " " + apiOperation.value() + " " + resultStr);
}
//Object[] args = joinPoint.getArgs();
logQueue.add(sysLogAudit);
@@ -116,10 +129,11 @@ public class LogAdvice implements ApplicationListener<ContextRefreshedEvent> {
try {
SysLogAudit log = logQueue.poll(5, TimeUnit.MILLISECONDS);
if (log != null) {
log.setSort(sysLogAuditService.getMaxSort() + 1);
sysLogAuditService.save(log);
}
} catch (Exception e) {
log.error("insert operation log to db error", e);
throw new BusinessException(LogResponseEnum.LOG_RECORD_FAILED);
}
}
}

View File

@@ -0,0 +1,28 @@
package com.njcn.gather.system.log.pojo.enums;
import lombok.Getter;
/**
* @author caozehui
* @data 2025-02-12
*/
@Getter
public enum LogLevelEnum {
DEBUG(1, "DEBUG"),
INFO(2, "INFO"),
WARN(3, "WARN"),
ERROR(4, "ERROR"),
FATAL(5, "FATAL");
private final int code;
private final String msg;
LogLevelEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
public static LogLevelEnum getEnum(int code) {
return LogLevelEnum.values()[code - 1];
}
}

View File

@@ -0,0 +1,18 @@
package com.njcn.gather.system.log.pojo.enums;
import lombok.Getter;
/**
* @author caozehui
* @data 2025-02-12
*/
@Getter
public enum LogOperationTypeEnum {
OPERATE("操作日志"),
WARNING("告警日志");
private String msg;
LogOperationTypeEnum(String msg) {
this.msg = msg;
}
}

View File

@@ -0,0 +1,21 @@
package com.njcn.gather.system.log.pojo.enums;
import lombok.Getter;
/**
* @author caozehui
* @data 2025-02-12
*/
@Getter
public enum LogResponseEnum {
LOG_RECORD_FAILED("A006001", "日志记录失败");
private final String code;
private final String message;
LogResponseEnum(String code, String message) {
this.message = message;
this.code = code;
}
}

View File

@@ -19,11 +19,10 @@ public class SysLogParam {
@Data
@EqualsAndHashCode(callSuper = true)
public static class QueryParam extends BaseParam {
@ApiModelProperty("操作类型")
@ApiModelProperty("日志类型")
private String operateType;
@ApiModelProperty("操作用户")
@Pattern(regexp = PatternRegex.SYSTEM_ID, message = SystemValidMessage.USER_ID_FORMAT_ERROR)
private String createBy;
}
}

View File

@@ -11,6 +11,7 @@ import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.Data;
import java.io.Serializable;
import java.math.BigInteger;
import java.time.LocalDateTime;
/**
@@ -62,6 +63,12 @@ public class SysLogAudit implements Serializable {
@TableField(fill = FieldFill.INSERT)
private String createBy;
/**
* 排序
*/
private Integer sort;
/**
* 创建时间
*/

View File

@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.gather.system.log.pojo.param.SysLogParam;
import com.njcn.gather.system.log.pojo.po.SysLogAudit;
import com.njcn.gather.system.log.pojo.vo.SysLogVO;
import io.swagger.models.auth.In;
import org.aspectj.lang.JoinPoint;
/**
@@ -23,6 +24,7 @@ public interface ISysLogAuditService extends IService<SysLogAudit> {
/**
* 导出审计日志数据
*
* @param param 查询参数
*/
void exportSysLogAuditData(SysLogParam.QueryParam param);
@@ -34,4 +36,19 @@ public interface ISysLogAuditService extends IService<SysLogAudit> {
* @return 成功返回true失败返回false
*/
//boolean addSysLogAudit(SysLogParam sysLogParam);
/**
* 保存登录、注销日志
*
* @param username 用户名
* @param type 1登录2注销
*/
void saveAuthLog(String username, Integer type);
/**
* 获取最大的排序值
*
* @return
*/
Integer getMaxSort();
}

View File

@@ -6,6 +6,8 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.gather.system.log.mapper.SysLogAuditMapper;
import com.njcn.gather.system.log.pojo.enums.LogLevelEnum;
import com.njcn.gather.system.log.pojo.enums.LogOperationTypeEnum;
import com.njcn.gather.system.log.pojo.param.SysLogParam;
import com.njcn.gather.system.log.pojo.po.SysLogAudit;
import com.njcn.gather.system.log.service.ISysLogAuditService;
@@ -13,12 +15,16 @@ import com.njcn.gather.system.log.util.CSVUtil;
import com.njcn.gather.user.user.pojo.po.SysUser;
import com.njcn.gather.user.user.service.ISysUserService;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.HttpServletUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@@ -40,11 +46,11 @@ public class SysLogAuditServiceImpl extends ServiceImpl<SysLogAuditMapper, SysLo
public Page<SysLogAudit> listSysLogAudit(SysLogParam.QueryParam param) {
QueryWrapper<SysLogAudit> queryWrapper = new QueryWrapper<>();
if (ObjectUtil.isNotNull(param)) {
queryWrapper.eq(StrUtil.isNotBlank(param.getOperateType()), "sys_log_audit.Operate_Type", param.getOperateType())
.eq(StrUtil.isNotBlank(param.getCreateBy()), "sys_log_audit.Create_By", param.getCreateBy())
queryWrapper.like(StrUtil.isNotBlank(param.getOperateType()), "sys_log_audit.Operate_Type", param.getOperateType())
.like(StrUtil.isNotBlank(param.getCreateBy()), "sys_log_audit.Create_By", param.getCreateBy())
.between(StrUtil.isAllNotBlank(param.getSearchBeginTime(), param.getSearchEndTime()), "sys_log_audit.Create_Time", param.getSearchBeginTime(), param.getSearchEndTime());
}
queryWrapper.orderByDesc("sys_log_audit.Create_Time");
queryWrapper.orderByDesc("sys_log_audit.Sort");
return this.page(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), queryWrapper);
}
@@ -64,7 +70,7 @@ public class SysLogAuditServiceImpl extends ServiceImpl<SysLogAuditMapper, SysLo
map.put("ip", item.getIp());
map.put("result", item.getResult());
map.put("remark", item.getRemark());
map.put("level", item.getLevel() == 0 ? "普通" : item.getLevel() == 1 ? "中等" : "严重");
map.put("level", LogLevelEnum.getEnum(item.getLevel()).getMsg());
map.put("warn", item.getWarn() == 0 ? "未告警" : "告警");
SysUser user = sysUserService.getById(item.getCreateBy());
map.put("createBy", ObjectUtil.isNull(user) ? "" : user.getName());
@@ -82,4 +88,33 @@ public class SysLogAuditServiceImpl extends ServiceImpl<SysLogAuditMapper, SysLo
// BeanUtils.copyProperties(sysLogParam, sysLogAudit);
// return this.save(sysLogAudit);
// }
@Override
@Transactional(rollbackFor = Exception.class)
public void saveAuthLog(String username, Integer type) {
SysLogAudit sysLogAudit = new SysLogAudit();
sysLogAudit.setOperateType(LogOperationTypeEnum.OPERATE.getMsg());
sysLogAudit.setLevel(LogLevelEnum.INFO.getCode());
sysLogAudit.setWarn(0);
HttpServletRequest request = HttpServletUtil.getRequest();
sysLogAudit.setIp(request.getRemoteAddr());
String typeStr = (type == 1 ? "登录" : "注销");
sysLogAudit.setResult(typeStr + "成功");
String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
sysLogAudit.setRemark(username + "用户:" + now + " " + typeStr + " 成功");
sysLogAudit.setSort(getMaxSort() + 1);
sysLogAudit.setCreateBy(username);
this.save(sysLogAudit);
}
@Override
public Integer getMaxSort() {
SysLogAudit log = this.lambdaQuery().orderByDesc(SysLogAudit::getSort).last("limit 1").one();
if (ObjectUtil.isNotNull(log)) {
return log.getSort();
}
return 0;
}
}