新增审计日志功能(支持spEL表达式)

This commit is contained in:
zlt
2020-02-04 17:35:47 +08:00
parent 5167a6b54f
commit 4d27926ee0
17 changed files with 485 additions and 11 deletions
@@ -37,5 +37,20 @@
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,20 @@
package com.central.log.annotation;
import java.lang.annotation.*;
/**
* @author zlt
* @date 2020/2/3
* <p>
* Blog: https://blog.csdn.net/zlt2000
* Github: https://github.com/zlt2000
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AuditLog {
/**
* 操作信息
*/
String operation();
}
@@ -0,0 +1,125 @@
package com.central.log.aspect;
import com.central.log.annotation.AuditLog;
import com.central.log.model.Audit;
import com.central.log.properties.AuditLogProperties;
import com.central.log.service.IAuditService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
/**
* 审计日志切面
*
* @author zlt
* @date 2020/2/3
* <p>
* Blog: https://blog.csdn.net/zlt2000
* Github: https://github.com/zlt2000
*/
@Slf4j
@Aspect
@ConditionalOnClass({HttpServletRequest.class, RequestContextHolder.class})
public class AuditLogAspect {
@Value("${spring.application.name}")
private String applicationName;
private AuditLogProperties auditLogProperties;
private IAuditService auditService;
public AuditLogAspect(AuditLogProperties auditLogProperties, IAuditService auditService) {
this.auditLogProperties = auditLogProperties;
this.auditService = auditService;
}
/**
* 用于SpEL表达式解析.
*/
private SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
/**
* 用于获取方法参数定义名字.
*/
private DefaultParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer();
@Before("@within(auditLog) || @annotation(auditLog)")
public void beforeMethod(JoinPoint joinPoint, AuditLog auditLog) {
//判断功能是否开启
if (auditLogProperties.getEnabled()) {
if (auditService == null) {
log.warn("AuditLogAspect - auditService is null");
return;
}
if (auditLog == null) {
// 获取类上的注解
auditLog = joinPoint.getTarget().getClass().getDeclaredAnnotation(AuditLog.class);
}
Audit audit = getAudit(auditLog, joinPoint);
auditService.save(audit);
}
}
/**
* 解析spEL表达式
*/
private String getValBySpEL(String spEL, MethodSignature methodSignature, Object[] args) {
//获取方法形参名数组
String[] paramNames = nameDiscoverer.getParameterNames(methodSignature.getMethod());
if (paramNames != null && paramNames.length > 0) {
Expression expression = spelExpressionParser.parseExpression(spEL);
// spring的表达式上下文对象
EvaluationContext context = new StandardEvaluationContext();
// 给上下文赋值
for(int i = 0; i < args.length; i++) {
context.setVariable(paramNames[i], args[i]);
}
return expression.getValue(context).toString();
}
return null;
}
/**
* 构建审计对象
*/
private Audit getAudit(AuditLog auditLog, JoinPoint joinPoint) {
Audit audit = new Audit();
audit.setTimestamp(LocalDateTime.now());
audit.setApplicationName(applicationName);
MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
audit.setClassName(methodSignature.getDeclaringTypeName());
audit.setMethodName(methodSignature.getName());
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String userId = request.getHeader("x-userid-header");
String userName = request.getHeader("x-user-header");
String clientId = request.getHeader("x-tenant-header");
audit.setUserId(userId);
audit.setUserName(userName);
audit.setClientId(clientId);
String operation = auditLog.operation();
if (operation.contains("#")) {
//获取方法参数值
Object[] args = joinPoint.getArgs();
operation = getValBySpEL(operation, methodSignature, args);
}
audit.setOperation(operation);
return audit;
}
}
@@ -1,5 +1,6 @@
package com.central.log.config;
import com.central.log.properties.AuditLogProperties;
import com.central.log.properties.TraceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@@ -9,7 +10,7 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
* @author zlt
* @date 2019/8/13
*/
@EnableConfigurationProperties(TraceProperties.class)
@EnableConfigurationProperties({TraceProperties.class, AuditLogProperties.class})
public class LogAutoConfigure {
}
@@ -0,0 +1,52 @@
package com.central.log.model;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
/**
* 审计日志
*
* @author zlt
* @date 2020/2/3
* <p>
* Blog: https://blog.csdn.net/zlt2000
* Github: https://github.com/zlt2000
*/
@Setter
@Getter
public class Audit {
/**
* 操作时间
*/
private LocalDateTime timestamp;
/**
* 应用名
*/
private String applicationName;
/**
* 类名
*/
private String className;
/**
* 方法名
*/
private String methodName;
/**
* 用户id
*/
private String userId;
/**
* 用户名
*/
private String userName;
/**
* 租户id
*/
private String clientId;
/**
* 操作信息
*/
private String operation;
}
@@ -0,0 +1,30 @@
package com.central.log.properties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
/**
* 审计日志配置
*
* @author zlt
* @date 2020/2/3
* <p>
* Blog: https://blog.csdn.net/zlt2000
* Github: https://github.com/zlt2000
*/
@Setter
@Getter
@ConfigurationProperties(prefix = "zlt.audit-log")
@RefreshScope
public class AuditLogProperties {
/**
* 是否开启审计日志
*/
private Boolean enabled = false;
/**
* 日志记录类型(logger/redis/db/es)
*/
private String logType;
}
@@ -0,0 +1,16 @@
package com.central.log.service;
import com.central.log.model.Audit;
/**
* 审计日志接口
*
* @author zlt
* @date 2020/2/3
* <p>
* Blog: https://blog.csdn.net/zlt2000
* Github: https://github.com/zlt2000
*/
public interface IAuditService {
void save(Audit audit);
}
@@ -0,0 +1,38 @@
package com.central.log.service.impl;
import com.central.log.model.Audit;
import com.central.log.service.IAuditService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import java.time.format.DateTimeFormatter;
/**
* 审计日志实现类-打印日志
*
* @author zlt
* @date 2020/2/3
* <p>
* Blog: https://blog.csdn.net/zlt2000
* Github: https://github.com/zlt2000
*/
@Slf4j
@Service
@ConditionalOnProperty(name = "zlt.audit-log.log-type", havingValue = "logger", matchIfMissing = true)
public class LoggerAuditServiceImpl implements IAuditService {
private static final String MSG_PATTERN = "{}|{}|{}|{}|{}|{}|{}|{}";
/**
* 格式为:{时间}|{应用名}|{类名}|{方法名}|{用户id}|{用户名}|{租户id}|{操作信息}
* 例子:2020-02-04 09:13:34.650|user-center|com.central.user.controller.SysUserController|saveOrUpdate|1|admin|webApp|新增用户:admin
*/
@Override
public void save(Audit audit) {
log.debug(MSG_PATTERN
, audit.getTimestamp().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))
, audit.getApplicationName(), audit.getClassName(), audit.getMethodName()
, audit.getUserId(), audit.getUserName(), audit.getClientId()
, audit.getOperation());
}
}
@@ -2,4 +2,5 @@ org.springframework.context.ApplicationContextInitializer=\
com.central.log.config.TtlMDCAdapterInitializer
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.central.log.config.LogAutoConfigure
com.central.log.config.LogAutoConfigure,\
com.central.log.aspect.AuditLogAspect
@@ -4,6 +4,7 @@
<springProperty name="APP_NAME" scope="context" source="spring.application.name"/>
<springProperty name="LOG_FILE" scope="context" source="logging.file" defaultValue="../logs/application/${APP_NAME}"/>
<springProperty name="LOG_POINT_FILE" scope="context" source="logging.file" defaultValue="../logs/point"/>
<springProperty name="LOG_AUDIT_FILE" scope="context" source="logging.file" defaultValue="../logs/audit"/>
<springProperty name="LOG_MAXFILESIZE" scope="context" source="logback.filesize" defaultValue="50MB"/>
<springProperty name="LOG_FILEMAXDAY" scope="context" source="logback.filemaxday" defaultValue="7"/>
<springProperty name="ServerIP" scope="context" source="spring.cloud.client.ip-address" defaultValue="0.0.0.0"/>
@@ -64,9 +65,23 @@
<maxFileSize>${LOG_MAXFILESIZE}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
</filter>
</appender>
<appender name="audit_log" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_AUDIT_FILE}/audit.log</file>
<encoder>
<pattern>%msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 基于时间的分包策略 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_AUDIT_FILE}/audit.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<!--保留时间,单位:天-->
<maxHistory>${LOG_FILEMAXDAY}</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${LOG_MAXFILESIZE}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<appender name="point_log_async" class="ch.qos.logback.classic.AsyncAppender">
@@ -77,9 +92,16 @@
<discardingThreshold>0</discardingThreshold>
<appender-ref ref="FileAppender"/>
</appender>
<appender name="audit_log_async" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<appender-ref ref="audit_log"/>
</appender>
<logger name="com.central.log.monitor" level="debug" addtivity="false">
<appender-ref ref="point_log_async" />
</logger>
<logger name="com.central.log.service.impl.LoggerAuditServiceImpl" level="debug" addtivity="false">
<appender-ref ref="audit_log_async" />
</logger>
<root level="INFO">
<appender-ref ref="StdoutAppender"/>