springboot cloud,不同模块,记录接口操作日志

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介: springboot cloud,不同模块,记录接口操作日志

Spring Boot Cloud 中实现请求接口操作记录通常涉及多个模块和组件。可以使用 Spring Boot 提供的功能以及 Spring Cloud 的一些组件来完成这个任务。

1. 架构设计

假设你的系统包括以下模块:

  • API Gateway:接收客户端请求并路由到不同的服务。
  • Service AService B:具体的业务服务模块。
  • Logging Service:用于集中存储和管理操作日志的服务。

我们将通过以下步骤实现请求接口操作记录:

  1. API Gateway:拦截请求并将操作信息传递到日志服务。
  2. Service A / Service B:在处理请求时记录操作信息。
  3. Logging Service:接收并存储日志信息。

2. 关键代码示例

2.1 API Gateway

使用 Spring Cloud Gateway 实现 API Gateway,并在网关中记录日志。

pom.xml(依赖)

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>

GatewayConfig.java(配置)

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
 
@Configuration
public class GatewayConfig {
 
    @Bean
    public LoggingFilter loggingFilter() {
        return new LoggingFilter();
    }
 
    public static class LoggingFilter extends AbstractGatewayFilterFactory<Object> {
        
        public LoggingFilter() {
            super(Object.class);
        }
 
        @Override
        public GatewayFilter apply(Object config) {
            return (exchange, chain) -> {
                logRequest(exchange);
                return chain.filter(exchange).then(Mono.fromRunnable(() -> logResponse(exchange)));
            };
        }
 
        private void logRequest(ServerWebExchange exchange) {
            String path = exchange.getRequest().getURI().getPath();
            // Log request details (e.g., using a logging framework)
            System.out.println("Request Path: " + path);
        }
 
        private void logResponse(ServerWebExchange exchange) {
            // Log response details
            System.out.println("Response Status: " + exchange.getResponse().getStatusCode());
        }
    }
}
2.2 Service A / Service B

在每个服务中,可以使用 Spring AOP 来记录请求的操作信息。

pom.xml(依赖)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

LoggingAspect.java切面

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
 
@Aspect
@Component
public class LoggingAspect {
 
    @AfterReturning(pointcut = "execution(* com.example.service..*(..))", returning = "result")
    public void logAfter(JoinPoint joinPoint, Object result) {
        // Log method execution details
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Method: " + methodName + " executed with result: " + result);
        // You can also log additional information like arguments or execution time
    }
}
2.3 Logging Service

记录日志到集中存储(如数据库或 Elasticsearch)。

pom.xml(依赖)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

LogEntry.java(日志实体)

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
 
@Document(collection = "logs")
public class LogEntry {
 
    @Id
    private String id;
    private String message;
    private String level;
    private long timestamp;
 
    // Getters and setters
}

LogRepository.java(日志存储)

import org.springframework.data.mongodb.repository.MongoRepository;
 
public interface LogRepository extends MongoRepository<LogEntry, String> {
}

LogService.java(日志服务)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
@Service
public class LogService {
 
    @Autowired
    private LogRepository logRepository;
 
    public void saveLog(String message, String level) {
        LogEntry logEntry = new LogEntry();
        logEntry.setMessage(message);
        logEntry.setLevel(level);
        logEntry.setTimestamp(System.currentTimeMillis());
        logRepository.save(logEntry);
    }
}

LoggingController.java(接收日志)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class LoggingController {
 
    @Autowired
    private LogService logService;
 
    @PostMapping("/log")
    public void log(@RequestBody LogEntry logEntry) {
        logService.saveLog(logEntry.getMessage(), logEntry.getLevel());
    }
}

3. 整合与测试

确保所有模块能够正常交互,API Gateway 发送请求到业务服务,业务服务记录日志并将其发送到日志服务。你可以使用 Postman 或类似工具来测试 API Gateway 和业务服务的接口。

4. 总结

以上代码展示了如何在 Spring Boot Cloud 环境中实现请求接口操作记录。实际应用中,你可能需要根据具体需求进行更多的定制和优化。


相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
相关文章
|
3月前
|
Java 中间件
SpringBoot入门(6)- 添加Logback日志
SpringBoot入门(6)- 添加Logback日志
136 5
|
4天前
|
监控 Java Spring
SpringBoot:SpringBoot通过注解监测Controller接口
本文详细介绍了如何通过Spring Boot注解监测Controller接口,包括自定义注解、AOP切面的创建和使用以及具体的示例代码。通过这种方式,可以方便地在Controller方法执行前后添加日志记录、性能监控和异常处理逻辑,而无需修改方法本身的代码。这种方法不仅提高了代码的可维护性,还增强了系统的监控能力。希望本文能帮助您更好地理解和应用Spring Boot中的注解监测技术。
33 16
|
1月前
|
开发框架 运维 监控
Spring Boot中的日志框架选择
在Spring Boot开发中,日志管理至关重要。常见的日志框架有Logback、Log4j2、Java Util Logging和Slf4j。选择合适的日志框架需考虑性能、灵活性、社区支持及集成配置。本文以Logback为例,演示了如何记录不同级别的日志消息,并强调合理配置日志框架对提升系统可靠性和开发效率的重要性。
|
1月前
|
存储 安全 Java
Spring Boot 3 集成Spring AOP实现系统日志记录
本文介绍了如何在Spring Boot 3中集成Spring AOP实现系统日志记录功能。通过定义`SysLog`注解和配置相应的AOP切面,可以在方法执行前后自动记录日志信息,包括操作的开始时间、结束时间、请求参数、返回结果、异常信息等,并将这些信息保存到数据库中。此外,还使用了`ThreadLocal`变量来存储每个线程独立的日志数据,确保线程安全。文中还展示了项目实战中的部分代码片段,以及基于Spring Boot 3 + Vue 3构建的快速开发框架的简介与内置功能列表。此框架结合了当前主流技术栈,提供了用户管理、权限控制、接口文档自动生成等多项实用特性。
81 8
|
4月前
|
存储 算法 安全
SpringBoot 接口加密解密实现
【10月更文挑战第18天】
|
3月前
|
Java 中间件
SpringBoot入门(6)- 添加Logback日志
SpringBoot入门(6)- 添加Logback日志
73 1
|
3月前
|
JSON Java 数据库
SpringBoot项目使用AOP及自定义注解保存操作日志
SpringBoot项目使用AOP及自定义注解保存操作日志
76 1
|
3月前
|
Java 开发者 Spring
精通SpringBoot:16个扩展接口精讲
【10月更文挑战第16天】 SpringBoot以其简化的配置和强大的扩展性,成为了Java开发者的首选框架之一。SpringBoot提供了一系列的扩展接口,使得开发者能够灵活地定制和扩展应用的行为。掌握这些扩展接口,能够帮助我们写出更加优雅和高效的代码。本文将详细介绍16个SpringBoot的扩展接口,并探讨它们在实际开发中的应用。
68 1
|
4月前
|
存储 安全 Java
|
5月前
|
SQL JSON Java
springboot 如何编写增删改查后端接口,小白极速入门,附完整代码
本文为Spring Boot增删改查接口的小白入门教程,介绍了项目的构建、配置YML文件、代码编写(包括实体类、Mapper接口、Mapper.xml、Service和Controller)以及使用Postman进行接口测试的方法。同时提供了SQL代码和完整代码的下载链接。
springboot 如何编写增删改查后端接口,小白极速入门,附完整代码