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日志并进行多维度分析。
相关文章
|
12天前
|
Java Maven Spring
SpringBoot日志整合
SpringBoot日志整合
11 2
|
18天前
|
数据采集 监控 Java
SpringBoot日志全方位超详细手把手教程,零基础可学习 日志如何配置及SLF4J的使用......
本文是关于SpringBoot日志的详细教程,涵盖日志的定义、用途、SLF4J框架的使用、日志级别、持久化、文件分割及格式配置等内容。
37 0
SpringBoot日志全方位超详细手把手教程,零基础可学习 日志如何配置及SLF4J的使用......
|
1月前
|
Prometheus Cloud Native Go
Golang语言之Prometheus的日志模块使用案例
这篇文章是关于如何在Golang语言项目中使用Prometheus的日志模块的案例,包括源代码编写、编译和测试步骤。
35 3
Golang语言之Prometheus的日志模块使用案例
|
29天前
|
SQL JSON Java
springboot 如何编写增删改查后端接口,小白极速入门,附完整代码
本文为Spring Boot增删改查接口的小白入门教程,介绍了项目的构建、配置YML文件、代码编写(包括实体类、Mapper接口、Mapper.xml、Service和Controller)以及使用Postman进行接口测试的方法。同时提供了SQL代码和完整代码的下载链接。
springboot 如何编写增删改查后端接口,小白极速入门,附完整代码
|
29天前
|
存储 前端开发 Java
springboot文件上传和下载接口的简单思路
本文介绍了在Spring Boot中实现文件上传和下载接口的简单思路。文件上传通过`MultipartFile`对象获取前端传递的文件并存储,返回对外访问路径;文件下载通过文件的uuid名称读取文件,并通过流的方式输出,实现文件下载功能。
springboot文件上传和下载接口的简单思路
|
12天前
|
SQL XML 监控
SpringBoot框架日志详解
本文详细介绍了日志系统的重要性及其在不同环境下的配置方法。日志用于记录系统运行时的问题,确保服务的可靠性。文章解释了各种日志级别(如 info、warn、error 等)的作用,并介绍了常用的日志框架如 SLF4J 和 Logback。此外,还说明了如何在 SpringBoot 中配置日志输出路径及日志级别,包括控制台输出与文件输出的具体设置方法。通过这些配置,开发者能够更好地管理和调试应用程序。
|
1月前
|
Java
日志框架log4j打印异常堆栈信息携带traceId,方便接口异常排查
日常项目运行日志,异常栈打印是不带traceId,导致排查问题查找异常栈很麻烦。
|
1月前
|
存储 数据采集 Java
Spring Boot 3 实现GZIP压缩优化:显著减少接口流量消耗!
在Web开发过程中,随着应用规模的扩大和用户量的增长,接口流量的消耗成为了一个不容忽视的问题。为了提升应用的性能和用户体验,减少带宽占用,数据压缩成为了一个重要的优化手段。在Spring Boot 3中,通过集成GZIP压缩技术,我们可以显著减少接口流量的消耗,从而优化应用的性能。本文将详细介绍如何在Spring Boot 3中实现GZIP压缩优化。
151 6
|
23天前
|
存储 NoSQL Java
Spring Boot项目中使用Redis实现接口幂等性的方案
通过上述方法,可以有效地在Spring Boot项目中利用Redis实现接口幂等性,既保证了接口操作的安全性,又提高了系统的可靠性。
22 0
|
1月前
|
运维 NoSQL Java
SpringBoot接入轻量级分布式日志框架GrayLog技术分享
在当今的软件开发环境中,日志管理扮演着至关重要的角色,尤其是在微服务架构下,分布式日志的统一收集、分析和展示成为了开发者和运维人员必须面对的问题。GrayLog作为一个轻量级的分布式日志框架,以其简洁、高效和易部署的特性,逐渐受到广大开发者的青睐。本文将详细介绍如何在SpringBoot项目中接入GrayLog,以实现日志的集中管理和分析。
160 1