diff --git a/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java b/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java
index b8612e46..0db93f8b 100644
--- a/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java
+++ b/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java
@@ -12,6 +12,8 @@ import com.central.common.annotation.LoginUser;
import com.central.common.constant.CommonConstant;
import com.central.common.model.*;
import com.central.common.utils.ExcelUtil;
+//import com.central.log.annotation.AuditLog;
+import com.central.log.annotation.AuditLog;
import com.central.search.client.service.IQueryService;
import com.central.search.model.LogicDelDto;
import com.central.search.model.SearchDto;
@@ -118,7 +120,8 @@ public class SysUserController {
* @param sysUser
*/
@PutMapping("/users")
- @CachePut(value = "user", key = "#sysUser.username")
+ @CachePut(value = "user", key = "#sysUser.username", unless="#result == null")
+ //@AuditLog(operation = "'更新用户:' + #sysUser")
public void updateSysUser(@RequestBody SysUser sysUser) {
appUserService.updateById(sysUser);
}
@@ -187,6 +190,7 @@ public class SysUserController {
* @param id
*/
@PutMapping(value = "/users/{id}/password")
+ //@AuditLog(operation = "'重置用户密码:' + #id")
public Result resetPassword(@PathVariable Long id) {
if (checkAdmin(id)) {
return Result.failed(ADMIN_CHANGE_MSG);
@@ -213,6 +217,7 @@ public class SysUserController {
* @param id
*/
@DeleteMapping(value = "/users/{id}")
+ //@AuditLog(operation = "'删除用户:' + #id")
public Result delete(@PathVariable Long id) {
if (checkAdmin(id)) {
return Result.failed(ADMIN_CHANGE_MSG);
@@ -230,6 +235,7 @@ public class SysUserController {
*/
@CacheEvict(value = "user", key = "#sysUser.username")
@PostMapping("/users/saveOrUpdate")
+ @AuditLog(operation = "'新增或更新用户:' + #sysUser.username")
public Result saveOrUpdate(@RequestBody SysUser sysUser) {
return appUserService.saveOrUpdateUser(sysUser);
}
diff --git a/zlt-business/user-center/src/main/resources/application.yml b/zlt-business/user-center/src/main/resources/application.yml
index 630192bc..bff4c5bd 100644
--- a/zlt-business/user-center/src/main/resources/application.yml
+++ b/zlt-business/user-center/src/main/resources/application.yml
@@ -34,4 +34,7 @@ zlt:
- sys_role_user
- sys_role_menu
ignoreSqls:
- - com.central.user.mapper.SysRoleMapper.findAll
\ No newline at end of file
+ - com.central.user.mapper.SysRoleMapper.findAll
+ #审计日志
+# audit-log:
+# enabled: true
\ No newline at end of file
diff --git a/zlt-business/user-center/src/test/java/com/central/user/controller/SysUserControllerTest.java b/zlt-business/user-center/src/test/java/com/central/user/controller/SysUserControllerTest.java
index e6137ae3..dd191ca7 100644
--- a/zlt-business/user-center/src/test/java/com/central/user/controller/SysUserControllerTest.java
+++ b/zlt-business/user-center/src/test/java/com/central/user/controller/SysUserControllerTest.java
@@ -2,6 +2,8 @@ package com.central.user.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -80,7 +82,36 @@ public class SysUserControllerTest {
@Transactional
public void whenDeleteSuccess() throws Exception {
mockMvc.perform(delete("/users/1")
+ .header("x-userid-header", 1)
+ .header("x-user-header", "admin")
+ .header("x-tenant-header", "webApp")
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
}
+
+ @Test
+ @Transactional
+ public void whenSaveOrUpdateSuccess() throws Exception {
+ String content = "{\"id\":1, \"username\":\"admin\", \"roleId\":\"1,2,3\"}";
+ mockMvc.perform(post("/users/saveOrUpdate")
+ .header("x-userid-header", 1)
+ .header("x-user-header", "admin")
+ .header("x-tenant-header", "webApp")
+ .contentType(MediaType.APPLICATION_JSON_UTF8)
+ .content(content))
+ .andExpect(status().isOk());
+ }
+
+ @Test
+ @Transactional
+ public void whenUpdateSuccess() throws Exception {
+ String content = "{\"id\":1, \"username\":\"admin\", \"roleId\":\"1,2,3\"}";
+ mockMvc.perform(put("/users")
+ .header("x-userid-header", 1)
+ .header("x-user-header", "admin")
+ .header("x-tenant-header", "webApp")
+ .contentType(MediaType.APPLICATION_JSON_UTF8)
+ .content(content))
+ .andExpect(status().isOk());
+ }
}
diff --git a/zlt-commons/zlt-log-spring-boot-starter/pom.xml b/zlt-commons/zlt-log-spring-boot-starter/pom.xml
index f7473c37..ace3e2ba 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/pom.xml
+++ b/zlt-commons/zlt-log-spring-boot-starter/pom.xml
@@ -37,5 +37,20 @@
+ * 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(); +} diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/aspect/AuditLogAspect.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/aspect/AuditLogAspect.java new file mode 100644 index 00000000..a4cd4686 --- /dev/null +++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/aspect/AuditLogAspect.java @@ -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 + *
+ * 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; + } +} diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/config/LogAutoConfigure.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/config/LogAutoConfigure.java index 73575311..95e2c6c4 100644 --- a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/config/LogAutoConfigure.java +++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/config/LogAutoConfigure.java @@ -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 { } diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/model/Audit.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/model/Audit.java new file mode 100644 index 00000000..622cc55a --- /dev/null +++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/model/Audit.java @@ -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 + *
+ * 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; +} diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/properties/AuditLogProperties.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/properties/AuditLogProperties.java new file mode 100644 index 00000000..af73dd17 --- /dev/null +++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/properties/AuditLogProperties.java @@ -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 + *
+ * 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; +} diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/IAuditService.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/IAuditService.java new file mode 100644 index 00000000..fdefd1ef --- /dev/null +++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/IAuditService.java @@ -0,0 +1,16 @@ +package com.central.log.service; + +import com.central.log.model.Audit; + +/** + * 审计日志接口 + * + * @author zlt + * @date 2020/2/3 + *
+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +public interface IAuditService { + void save(Audit audit); +} diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/impl/LoggerAuditServiceImpl.java b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/impl/LoggerAuditServiceImpl.java new file mode 100644 index 00000000..01099d1b --- /dev/null +++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/java/com/central/log/service/impl/LoggerAuditServiceImpl.java @@ -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 + *
+ * 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());
+ }
+}
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/META-INF/spring.factories
index 25b1a4a8..936d0a08 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/META-INF/spring.factories
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/META-INF/spring.factories
@@ -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
diff --git a/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/logback-spring.xml b/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/logback-spring.xml
index ca9fabc9..d4eec0b6 100644
--- a/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/logback-spring.xml
+++ b/zlt-commons/zlt-log-spring-boot-starter/src/main/resources/logback-spring.xml
@@ -4,6 +4,7 @@
+ * Blog: https://blog.csdn.net/zlt2000
+ * Github: https://github.com/zlt2000
+ */
+@RestController
+public class AuditLogController {
+ private final IQueryService queryService;
+
+ public AuditLogController(IQueryService queryService) {
+ this.queryService = queryService;
+ }
+
+ @ApiOperation(value = "审计日志全文搜索列表")
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = "page", value = "分页起始位置", required = true, dataType = "Integer"),
+ @ApiImplicitParam(name = "limit", value = "分页结束位置", required = true, dataType = "Integer"),
+ @ApiImplicitParam(name = "queryStr", value = "搜索关键字", dataType = "String")
+ })
+ @GetMapping(value = "/auditLog")
+ public PageResult审计日志
+
+
+