init aop log

This commit is contained in:
Chuck1sn
2025-07-07 16:13:52 +08:00
parent 5c685d4f74
commit 36d285a61d
22 changed files with 1741 additions and 44 deletions

View File

@@ -0,0 +1,45 @@
package com.zl.mjga.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 跳过AOP日志记录注解
*
* <p>在方法上添加此注解该方法将不会被AOP日志切面拦截和记录。
*
* <p>使用场景:
*
* <ul>
* <li>敏感操作方法,不希望记录日志
* <li>高频调用方法,避免产生过多日志
* <li>内部工具方法,不需要业务日志记录
* </ul>
*
* <p>使用示例:
*
* <pre>{@code
* @SkipAopLog
* public void sensitiveMethod() {
* // 此方法不会被AOP日志记录
* }
* }</pre>
*
* @author AOP Log System
* @since 1.0
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SkipAopLog {
/**
* 跳过日志记录的原因说明(可选)
*
* @return 跳过原因
*/
String reason() default "";
}

View File

@@ -0,0 +1,182 @@
package com.zl.mjga.aspect;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zl.mjga.annotation.SkipAopLog;
import com.zl.mjga.repository.UserRepository;
import com.zl.mjga.service.AopLogService;
import jakarta.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.Duration;
import java.time.Instant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.jooq.generated.mjga.tables.pojos.AopLog;
import org.jooq.generated.mjga.tables.pojos.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
@Aspect
@Component
@Slf4j
@RequiredArgsConstructor
public class LoggingAspect {
private final AopLogService aopLogService;
private final ObjectMapper objectMapper;
private final UserRepository userRepository;
@Around("execution(* com.zl.mjga.controller..*(..))")
public Object logController(ProceedingJoinPoint joinPoint) throws Throwable {
AopLog aopLog = new AopLog();
setRequestInfo(aopLog);
return processWithLogging(joinPoint, aopLog);
}
@Around("execution(* com.zl.mjga.service..*(..))")
public Object logService(ProceedingJoinPoint joinPoint) throws Throwable {
AopLog aopLog = new AopLog();
return processWithLogging(joinPoint, aopLog);
}
@Around("execution(* com.zl.mjga.repository..*(..))")
public Object logRepository(ProceedingJoinPoint joinPoint) throws Throwable {
AopLog aopLog = new AopLog();
return processWithLogging(joinPoint, aopLog);
}
private Object processWithLogging(ProceedingJoinPoint joinPoint, AopLog aopLog) throws Throwable {
if (shouldSkipLogging(joinPoint) || !isUserAuthenticated()) {
return joinPoint.proceed();
}
return logMethodExecution(joinPoint, aopLog);
}
private boolean shouldSkipLogging(ProceedingJoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
return method.isAnnotationPresent(SkipAopLog.class);
}
private boolean isUserAuthenticated() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication != null
&& authentication.isAuthenticated()
&& !"anonymousUser".equals(authentication.getName());
}
private Long getCurrentUserId() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = (String) authentication.getPrincipal();
User user = userRepository.fetchOneByUsername(username);
return user.getId();
}
private Object logMethodExecution(ProceedingJoinPoint joinPoint, AopLog aopLog) throws Throwable {
Instant startTime = Instant.now();
String className = joinPoint.getTarget().getClass().getSimpleName();
String methodName = joinPoint.getSignature().getName();
populateBasicLogInfo(aopLog, className, methodName, joinPoint.getArgs());
Object result = null;
Exception executionException = null;
try {
result = joinPoint.proceed();
aopLog.setReturnValue(serializeReturnValue(result));
} catch (Exception e) {
executionException = e;
aopLog.setErrorMessage(e.getMessage());
log.error("Method execution failed: {}.{}", className, methodName, e);
} finally {
aopLog.setExecutionTime(Duration.between(startTime, Instant.now()).toMillis());
aopLog.setSuccess(executionException == null);
saveLogSafely(aopLog);
}
if (executionException != null) {
throw executionException;
}
return result;
}
private void populateBasicLogInfo(
AopLog aopLog, String className, String methodName, Object[] args) {
aopLog.setClassName(className);
aopLog.setMethodName(methodName);
aopLog.setMethodArgs(serializeArgs(args));
aopLog.setUserId(getCurrentUserId());
}
private void saveLogSafely(AopLog aopLog) {
try {
aopLogService.saveLogAsync(aopLog);
} catch (Exception e) {
log.error(
"Failed to save AOP log for {}.{}", aopLog.getClassName(), aopLog.getMethodName(), e);
}
}
private void setRequestInfo(AopLog aopLog) {
ServletRequestAttributes attributes =
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes == null) {
return;
}
HttpServletRequest request = attributes.getRequest();
aopLog.setIpAddress(getClientIpAddress(request));
aopLog.setUserAgent(request.getHeader("User-Agent"));
}
private String getClientIpAddress(HttpServletRequest request) {
String xForwardedFor = request.getHeader("X-Forwarded-For");
if (xForwardedFor != null
&& !xForwardedFor.isEmpty()
&& !"unknown".equalsIgnoreCase(xForwardedFor)) {
return xForwardedFor.split(",")[0].trim();
}
String xRealIp = request.getHeader("X-Real-IP");
if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
return xRealIp;
}
return request.getRemoteAddr();
}
private String serializeArgs(Object[] args) {
if (ArrayUtils.isEmpty(args)) {
return null;
} else {
return serializeObject(args);
}
}
private String serializeReturnValue(Object returnValue) {
if (returnValue == null) {
return null;
} else {
return serializeObject(returnValue);
}
}
private String serializeObject(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
log.error("Failed to serialize {} ", obj, e);
return e.getMessage();
}
}
}

View File

@@ -0,0 +1,73 @@
package com.zl.mjga.controller;
import com.zl.mjga.dto.PageRequestDto;
import com.zl.mjga.dto.PageResponseDto;
import com.zl.mjga.dto.aoplog.AopLogQueryDto;
import com.zl.mjga.dto.aoplog.AopLogRespDto;
import com.zl.mjga.repository.AopLogRepository;
import com.zl.mjga.service.AopLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import java.time.OffsetDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/aop-log")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "AOP日志管理", description = "AOP日志查看和管理接口")
public class AopLogController {
private final AopLogService aopLogService;
private final AopLogRepository aopLogRepository;
@GetMapping("/page-query")
@ResponseStatus(HttpStatus.OK)
@Operation(summary = "分页查询AOP日志", description = "支持多种条件筛选的分页查询")
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).READ_USER_ROLE_PERMISSION)")
public PageResponseDto<List<AopLogRespDto>> pageQueryAopLogs(
@ModelAttribute @Valid PageRequestDto pageRequestDto,
@ModelAttribute AopLogQueryDto queryDto) {
return aopLogService.pageQueryAopLogs(pageRequestDto, queryDto);
}
@GetMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
@Operation(summary = "查询日志详情", description = "根据ID查询单条日志的详细信息")
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).READ_USER_ROLE_PERMISSION)")
public AopLogRespDto getAopLogById(@Parameter(description = "日志ID") @PathVariable Long id) {
return aopLogService.getAopLogById(id);
}
@DeleteMapping("/batch")
@ResponseStatus(HttpStatus.OK)
@Operation(summary = "批量删除日志", description = "根据ID列表批量删除日志")
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_USER_ROLE_PERMISSION)")
public int deleteAopLogs(@Parameter(description = "日志ID列表") @RequestBody List<Long> ids) {
return aopLogRepository.deleteByIds(ids);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
@Operation(summary = "删除单条日志", description = "根据ID删除单条日志")
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_USER_ROLE_PERMISSION)")
public void deleteAopLog(@Parameter(description = "日志ID") @PathVariable Long id) {
aopLogRepository.deleteById(id);
}
@DeleteMapping("/before")
@ResponseStatus(HttpStatus.OK)
@Operation(summary = "删除指定时间前的日志", description = "删除指定时间之前的所有日志")
@PreAuthorize("hasAuthority(T(com.zl.mjga.model.urp.EPermission).WRITE_USER_ROLE_PERMISSION)")
public int deleteLogsBeforeTime(
@Parameter(description = "截止时间") @RequestParam OffsetDateTime beforeTime) {
return aopLogService.deleteLogsBeforeTime(beforeTime);
}
}

View File

@@ -0,0 +1,43 @@
package com.zl.mjga.dto.aoplog;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/** AOP日志查询DTO */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AopLogQueryDto {
/** ID */
private Long id;
/** 类名 */
private String className;
/** 方法名 */
private String methodName;
/** 是否成功 */
private Boolean success;
/** 用户ID */
private Long userId;
/** IP地址 */
private String ipAddress;
/** 开始时间 */
private LocalDateTime startTime;
/** 结束时间 */
private LocalDateTime endTime;
/** 最小执行时间(毫秒) */
private Long minExecutionTime;
/** 最大执行时间(毫秒) */
private Long maxExecutionTime;
}

View File

@@ -0,0 +1,53 @@
package com.zl.mjga.dto.aoplog;
import java.time.OffsetDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AopLogRespDto {
/** 主键ID */
private Long id;
/** 类名 */
private String className;
/** 方法名 */
private String methodName;
/** 方法参数 */
private String methodArgs;
/** 返回值 */
private String returnValue;
/** 执行时间(毫秒) */
private Long executionTime;
/** 是否成功 */
private Boolean success;
/** 错误信息 */
private String errorMessage;
/** 用户ID */
private Long userId;
/** 用户名 */
private String username;
/** IP地址 */
private String ipAddress;
/** 用户代理 */
private String userAgent;
/** 创建时间 */
private OffsetDateTime createTime;
}

View File

@@ -1,6 +1,6 @@
package com.zl.mjga.model.urp;
public enum ChatMode {
NORMAL,
WITH_LIBRARY
NORMAL,
WITH_LIBRARY
}

View File

@@ -0,0 +1,117 @@
package com.zl.mjga.repository;
import static org.jooq.generated.mjga.tables.AopLog.AOP_LOG;
import static org.jooq.generated.mjga.tables.User.USER;
import static org.jooq.impl.DSL.*;
import com.zl.mjga.dto.PageRequestDto;
import com.zl.mjga.dto.aoplog.AopLogQueryDto;
import java.time.OffsetDateTime;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.jooq.*;
import org.jooq.Record;
import org.jooq.generated.mjga.tables.daos.AopLogDao;
import org.jooq.generated.mjga.tables.pojos.AopLog;
import org.jooq.impl.DSL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
/** AOP日志Repository */
@Repository
public class AopLogRepository extends AopLogDao {
@Autowired
public AopLogRepository(Configuration configuration) {
super(configuration);
}
public Result<Record> pageFetchBy(PageRequestDto pageRequestDto, AopLogQueryDto queryDto) {
return selectBy(queryDto)
.orderBy(pageRequestDto.getSortFields())
.limit(pageRequestDto.getSize())
.offset(pageRequestDto.getOffset())
.fetch();
}
public List<AopLog> fetchBy(AopLogQueryDto queryDto) {
return selectBy(queryDto).fetchInto(AopLog.class);
}
public SelectConditionStep<Record> selectBy(AopLogQueryDto queryDto) {
return ctx()
.select(AOP_LOG.asterisk(), USER.USERNAME, DSL.count().over().as("total_count"))
.from(AOP_LOG)
.leftJoin(USER)
.on(AOP_LOG.USER_ID.eq(USER.ID))
.where(buildConditions(queryDto));
}
private Condition buildConditions(AopLogQueryDto queryDto) {
Condition condition = noCondition();
if (queryDto == null) {
return condition;
}
// ID精确查询
if (queryDto.getId() != null) {
condition = condition.and(AOP_LOG.ID.eq(queryDto.getId()));
}
// 类名模糊查询
if (StringUtils.isNotBlank(queryDto.getClassName())) {
condition = condition.and(AOP_LOG.CLASS_NAME.like("%" + queryDto.getClassName() + "%"));
}
// 方法名模糊查询
if (StringUtils.isNotBlank(queryDto.getMethodName())) {
condition = condition.and(AOP_LOG.METHOD_NAME.like("%" + queryDto.getMethodName() + "%"));
}
// 成功状态
if (queryDto.getSuccess() != null) {
condition = condition.and(AOP_LOG.SUCCESS.eq(queryDto.getSuccess()));
}
// 用户ID
if (queryDto.getUserId() != null) {
condition = condition.and(AOP_LOG.USER_ID.eq(queryDto.getUserId()));
}
// IP地址模糊查询
if (StringUtils.isNotBlank(queryDto.getIpAddress())) {
condition = condition.and(AOP_LOG.IP_ADDRESS.like("%" + queryDto.getIpAddress() + "%"));
}
// 时间范围查询
if (queryDto.getStartTime() != null) {
OffsetDateTime startTime = queryDto.getStartTime().atOffset(OffsetDateTime.now().getOffset());
condition = condition.and(AOP_LOG.CREATE_TIME.ge(startTime));
}
if (queryDto.getEndTime() != null) {
OffsetDateTime endTime = queryDto.getEndTime().atOffset(OffsetDateTime.now().getOffset());
condition = condition.and(AOP_LOG.CREATE_TIME.le(endTime));
}
// 执行时间范围
if (queryDto.getMinExecutionTime() != null) {
condition = condition.and(AOP_LOG.EXECUTION_TIME.ge(queryDto.getMinExecutionTime()));
}
if (queryDto.getMaxExecutionTime() != null) {
condition = condition.and(AOP_LOG.EXECUTION_TIME.le(queryDto.getMaxExecutionTime()));
}
return condition;
}
public int deleteByIds(List<Long> ids) {
return ctx().deleteFrom(AOP_LOG).where(AOP_LOG.ID.in(ids)).execute();
}
public int deleteBeforeTime(OffsetDateTime beforeTime) {
return ctx().deleteFrom(AOP_LOG).where(AOP_LOG.CREATE_TIME.lt(beforeTime)).execute();
}
}

View File

@@ -0,0 +1,61 @@
package com.zl.mjga.service;
import com.zl.mjga.dto.PageRequestDto;
import com.zl.mjga.dto.PageResponseDto;
import com.zl.mjga.dto.aoplog.AopLogQueryDto;
import com.zl.mjga.dto.aoplog.AopLogRespDto;
import com.zl.mjga.repository.AopLogRepository;
import java.time.OffsetDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SelectConditionStep;
import org.jooq.generated.mjga.tables.pojos.AopLog;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Slf4j
@RequiredArgsConstructor
public class AopLogService {
private final AopLogRepository aopLogRepository;
@Async
public void saveLogAsync(AopLog aopLog) {
try {
aopLogRepository.insert(aopLog);
} catch (Exception e) {
log.error("Failed to save AOP log asynchronously", e);
}
}
public PageResponseDto<List<AopLogRespDto>> pageQueryAopLogs(
PageRequestDto pageRequestDto, AopLogQueryDto queryDto) {
Result<Record> records = aopLogRepository.pageFetchBy(pageRequestDto, queryDto);
if (records.isEmpty()) {
return PageResponseDto.empty();
}
List<AopLogRespDto> aopLogs = records.map((record -> record.into(AopLogRespDto.class)));
Long totalCount = records.get(0).getValue("total_count", Long.class);
return new PageResponseDto<>(totalCount, aopLogs);
}
public AopLogRespDto getAopLogById(Long id) {
AopLogQueryDto queryDto = new AopLogQueryDto();
queryDto.setId(id);
SelectConditionStep<Record> selectStep = aopLogRepository.selectBy(queryDto);
return selectStep.fetchOneInto(AopLogRespDto.class);
}
@Transactional
public int deleteLogsBeforeTime(OffsetDateTime beforeTime) {
return aopLogRepository.deleteBeforeTime(beforeTime);
}
}