- 1. 操作日志类
- 2. 自定义注解 @OperateLog
- 3. AOP 切面 OperateLogAspect
- 4. 工具类 OperationLogUtil
- 5. 打印日志 IOperationLogService
- 6. 配置类 OprLogRedisAutoConfiguration
- 7. 配置类 OperationLogAutoConfiguration
- 8. spring.factories配置
- 9. 使用自定义注解
- 10. 完整的工作流程
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString(exclude = "id")
public class OperationLog {
public static final boolean SUCCESS = true;
public static final boolean FAIL = false;
private int id;
private String username;
private String domainId;
private String userIp;
private String target;
private String action;
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime actionTime;
private boolean result;
private Long expired;
}
2. 自定义注解 @OperateLog
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
@Documented
public @interface OperateLog {
String target() default "";
String action() default "";
}
3. AOP 切面 OperateLogAspect
@Slf4j
@Component
@Aspect
public class OperateLogAspect {
@Pointcut("@annotation(com.sangfor.ngsoc.common.oprlog.annotation.OperateLog)")
public void operateLog() {
}
@Around("operateLog()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
// 1、目标方法执行之前,构造日志信息
long startTime = System.currentTimeMillis();
// 获取方法上@OperateLog注解的属性值,并构造OperationLog
OperationLog log = this.getAspectLogDescription(joinPoint);
getUserInfo(log);
try {
// 2、执行目标方法
Object proceed = joinPoint.proceed();
// 3、目标方法执行之后,打印操作日志
log.setExpired(System.currentTimeMillis() - startTime);
OperationLogUtil.success(log);
// 返回目标方法执行的返回值
return proceed;
} catch (Throwable throwable) {
log.setExpired(System.currentTimeMillis() - startTime);
OperationLogUtil.fail(log);
throw throwable;
}
}
private void getUserInfo(OperationLog log) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
log.setUsername(ClientUtils.getClientAccount(attributes.getRequest()));
log.setUserIp(ClientUtils.getClientIp(attributes.getRequest()));
}
}
private OperationLog getAspectLogDescription(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
// 通过注解作为切面进入,此处注解应该不会为空
OperateLog annotation = method.getAnnotation(OperateLog.class);
return new OperationLog(null, null, i18n(annotation.target()), i18n(annotation.action()), OperationLog.FAIL);
}
private String i18n(String i18nkey) {
try {
return I18nUtils.i18n(i18nkey);
} catch (NoSuchMessageException e) {
return i18nkey;
}
}
}
4. 工具类 OperationLogUtil
public class OperationLogUtil {
private static IOperationLogService service;
@Autowired
public void setOperationLogService(IOperationLogService service) {
OperationLogUtil.service = service;
}
public static void success(OperationLog operationLog) {
operationLog.setResult(OperationLog.SUCCESS);
log(operationLog);
}
public static void fail(OperationLog operationLog) {
operationLog.setResult(OperationLog.FAIL);
log(operationLog);
}
public static void log(OperationLog operationLog) {
service.saveLog(operationLog);
}
}
@Slf4j
public class ClientUtils {
private static final String UNKNOWN = "unknown";
private static final String LOCALHOST = "127.0.0.1";
private static final Pattern IP_PATTERN = Pattern.compile("((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}");
public static String getClientIp(HttpServletRequest request) {
String ipAddress;
try {
ipAddress = request.getHeader("y-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress) || !IP_PATTERN.matcher(ipAddress).matches()) {
ipAddress = request.getRemoteAddr();
if (LOCALHOST.equals(ipAddress)) {
InetAddress inet = InetAddress.getLocalHost();
ipAddress = inet.getHostAddress();
}
}
} catch (UnknownHostException e) {
ipAddress = "";
}
return ipAddress;
}
public static String getClientAccount(HttpServletRequest request) {
Principal userPrincipal = request.getUserPrincipal();
if (Objects.nonNull(userPrincipal)) {
OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) userPrincipal;
JSONObject jsonObject = JSONUtil.parseObj(oAuth2Authentication.getUserAuthentication().getPrincipal());
JSONObject userObject = (JSONObject) jsonObject.get(ClientConstans.USER_INFO_KEY);
String username = String.valueOf(userObject.get(ClientConstans.USER_NAME_KEY));
return username;
}
return null;
}
public static String getClientUserId(HttpServletRequest request) {
Principal userPrincipal = request.getUserPrincipal();
if (Objects.nonNull(userPrincipal)) {
return userPrincipal.getName();
}
return null;
}
public static String getHostIp() {
String tempIp = LOCALHOST;
try {
tempIp = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e1) {
log.error("unknown host error ", e1);
}
try {
Enumeration networks = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
Enumeration addrs;
while (networks.hasMoreElements()) {
addrs = networks.nextElement().getInetAddresses();
while (addrs.hasMoreElements()) {
ip = addrs.nextElement();
if (ip != null
&& ip instanceof Inet4Address
&& ip.isSiteLocalAddress()
&& !ip.getHostAddress().equals(tempIp)) {
return ip.getHostAddress();
}
}
}
return tempIp;
} catch (SocketException e) {
log.error("Failed getting network interface error ", e);
}
return tempIp;
}
}
5. 打印日志 IOperationLogService
public interface IOperationLogService {
void saveLog(OperationLog operationLog);
}
@Slf4j
public class ConsoleOperationLogServiceImpl implements IOperationLogService {
@Override
public void saveLog(OperationLog operationLog) {
log.info("[OperationLog]: {}", operationLog);
}
}
@Slf4j
@RequiredArgsConstructor
public class RedisOperationLogServiceImpl extends ConsoleOperationLogServiceImpl {
private final static String OPR_LOG_CHANEL = "opr_log_chanel";
private final RedisTemplate redisTemplate;
@Override
public void saveLog(OperationLog operationLog) {
super.saveLog(operationLog);
redisTemplate.opsForList().rightPush(OPR_LOG_CHANEL, operationLog);
}
}
6. 配置类 OprLogRedisAutoConfiguration
@Configuration
public class OprLogRedisAutoConfiguration {
@Bean(name = "oprLogRedisTempalte")
@ConditionalOnProperty(prefix = "spring.redis", value = { "host", "password" })
public RedisTemplate oprLogRedisTempalte(RedisConnectionFactory connectionFactory) {
RedisTemplate template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
return template;
}
}
配置文件application.yml中的配置:
spring:
application:
name: activiti-
#redis的配置
redis:
host: 10.87.67.226
database: 0
port: 6379
password: 59c8ef0e019981ad
7. 配置类 OperationLogAutoConfiguration
@Configuration
@AutoConfigureAfter(OprLogRedisAutoConfiguration.class)
public class OperationLogAutoConfiguration {
@Bean
@Qualifier("oprLogRedisTempalte")
@ConditionalOnBean(name = "oprLogRedisTempalte")
public IOperationLogService operationLogService(RedisTemplate redisTemplate) {
return new RedisOperationLogServiceImpl(redisTemplate);
}
@Bean
@ConditionalOnMissingBean(name = "oprLogRedisTempalte")
public IOperationLogService operationLogService() {
return new ConsoleOperationLogServiceImpl();
}
@Bean
public OperationLogUtil operationLogUtil() {
return new OperationLogUtil();
}
@Bean
@ConditionalOnMissingBean
public OperateLogAspect operateLogAspect() {
return new OperateLogAspect();
}
}
8. spring.factories配置
# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration= com.sangfor.ngsoc.common.oprlog.autoconfig.OprLogRedisAutoConfiguration, com.sangfor.ngsoc.common.oprlog.autoconfig.OperationLogAutoConfiguration
如果想将日志报存,可以使用ORM框架保存到数据库表中:
CREATE TABLE IF NOT EXISTS `t_opr_log` ( `id` int UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '操作id', `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '操作用户', `userIp` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '操作用户所在的ip,如果是后台定时任务的操作或者其他没有ip的操作,为null', `target` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '被操作对象', `action` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '操作动作', `actionTime` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '操作时间', `result` tinyint(1) NOT NULL COMMENT '结果,成功或者失败,1表示成功,0表示失败', PRIMARY KEY (`id`) USING BTREE, )9. 使用自定义注解
@Api(tags = "工作组分类管理")
@RestController
@RequestMapping("/api/v1")
@Slf4j
@ResponseResult
public class GroupCategoryController {
@Autowired
private GroupCategoryService groupCategoryService;
@OperateLog(target = "auth.group.category", action = "auth.group.category.list.get")
@GetMapping("/groupCategory")
public GroupTreeVo groupCategoryList() {
return groupCategoryService.getList();
}
}
控制台打印的操作日志信息:
10. 完整的工作流程OperationLog(username=sysadmin, domainId=null, userIp=10.32.39.74, target=auth.group.category, action=auth.group.category.list.get, actionTime=2022-06-08T15:00:16.819618, result=true, expired=182522)
@OperateLog(target = "auth.group.category", action = "auth.group.category.list.get")
@GetMapping("/groupCategory")
public GroupTreeVo groupCategoryList() {
return groupCategoryService.getList();
}
① 执行加了@OperateLog注解的方法时,会被Spring AOP中的拦截器拦截。
② 执行AOP切面的中目标方法的前置增强。
③ 执行AOP切面的中目标方法。
④ 执行AOP切面的中目标方法的后置增强。
@Slf4j
@Component
@Aspect
public class OperateLogAspect {
@Pointcut("@annotation(com.sangfor.ngsoc.common.oprlog.annotation.OperateLog)")
public void operateLog() {
}
@Around("operateLog()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
// 1、目标方法执行之前,构造日志信息
long startTime = System.currentTimeMillis();
// 获取方法上@OperateLog注解的属性值,并构造OperationLog
OperationLog log = this.getAspectLogDescription(joinPoint);
getUserInfo(log);
try {
// 2、执行目标方法
Object proceed = joinPoint.proceed();
// 3、目标方法执行之后,打印操作日志
log.setExpired(System.currentTimeMillis() - startTime);
OperationLogUtil.success(log);
// 返回目标方法执行的返回值
return proceed;
} catch (Throwable throwable) {
log.setExpired(System.currentTimeMillis() - startTime);
OperationLogUtil.fail(log);
throw throwable;
}
}
}
⑤ 目标方法执行成功时,记录日志:
public class OperationLogUtil {
private static IOperationLogService service;
@Autowired
public void setOperationLogService(IOperationLogService service) {
OperationLogUtil.service = service;
}
public static void success(OperationLog operationLog) {
operationLog.setResult(OperationLog.SUCCESS);
log(operationLog);
}
public static void fail(OperationLog operationLog) {
operationLog.setResult(OperationLog.FAIL);
log(operationLog);
}
public static void log(OperationLog operationLog) {
service.saveLog(operationLog);
}
}
⑥ 因为配置文件中配置了
spring:
#redis的配置
redis:
host: 10.87.67.226
database: 0
port: 6379
password: 59c8ef0e019981ad
因此容器中会注入operationLogService、oprLogRedisTempalte,因此执行的是下面的方法
@Slf4j
@RequiredArgsConstructor
public class RedisOperationLogServiceImpl extends ConsoleOperationLogServiceImpl {
private final static String OPR_LOG_CHANEL = "opr_log_chanel";
private final RedisTemplate redisTemplate;
@Override
public void saveLog(OperationLog operationLog) {
super.saveLog(operationLog);
redisTemplate.opsForList().rightPush(OPR_LOG_CHANEL, operationLog);
}
}
⑦ 如果没有配置redis相关信息,那么将会执行:
@Slf4j
public class ConsoleOperationLogServiceImpl implements IOperationLogService {
@Override
public void saveLog(OperationLog operationLog) {
log.info("[OperationLog]: {}", operationLog);
}
}



