Spring Cloud Sleuth (2)-与ELK集成

通过Spring Cloud Sleuth (1)-入门篇我们已经引入了Sleuth的基础模块完成一次任务链的跟踪,但是由于日志文件都离散的存储在各个微服务结点上,日常运维时仅仅通过查看日志文件来分析定位问题还是一件繁琐的问题。所以我们需要一些工具来收集、存储、分析和展示日志信息,例如ELKElasticSearchLogstashkibana)组件。

 

Spring Cloud SleuthELK整合时实际上只要与Logstash对接既可,所以我们要为Logstash准备好Json格式的日志信息。SpringBoot默认使用logback来记录日志,而Logstash自身也有对logback日志工具的支持工具,所以可以直接通过在logback配置中增加LogstashAppender来非常方便的将日志转化为Json的格式存储和输出了。

 

Spring Cloud SleuthLogstash的直接集成有两种方式:

Logstash与微服务应用安装在一起,监听日志文件

Logstash 独立部署,微服务节点通过网络向 Logstash 发送日志信息。

之所以上面用了直接这个词,因为还存在间接形式的变种,微服务将日志发送给Redis或者MQ,再由他们去对接Logstash


实例代码:

Eureka-Serverhttps://github.com/yejingtao/forblog/tree/master/demo-eureka-register

ELK-Trace1https://github.com/yejingtao/forblog/tree/master/demo-elk-trace1

ELK-Trace2https://github.com/yejingtao/forblog/tree/master/demo-elk-trace2


先看如何实现日志的Json格式化:

Pom.xml 中增加 logstash 的组件
<dependency>
            <groupId>net.logstash.logback</groupId>
            <artifactId>logstash-logback-encoder</artifactId>
            <version>4.6</version>
        </dependency>

/resources下个配置文件

application.ymlspring boot的配置信息

logback-spring.xmllogstash集成的配置信息,在我的项目中项目跟目录下和/src/main/resources下各有一个logback-spring.xml文件,分别代表两种部署方式。

bootstrap.properties:里面只有一行配置,是logback-spring.xml中需要到的参数,由于logback-spring.xml的加载在application.yml之前,所以讲spring.application.name的配置信息定义在最先加载的bootstrap.properties文件中。

剩下的代码参考Spring Cloud Sleuth (1)-入门篇没有任何改造。

先使用项目根目录下的 logback-spring.xml文件来启动验证。
<?xml version="1.0" encoding="UTF-8"?>
<!--该日志将日志级别不同的log信息保存到不同的文件中 -->
<configuration>
	<include resource="org/springframework/boot/logging/logback/defaults.xml" />

	<springProperty scope="context" name="springAppName"
		source="spring.application.name" />

	<!-- 日志在工程中的输出位置 -->
	<property name="LOG_FILE" value="${BUILD_FOLDER:-build}/${springAppName}" />

	<!-- 控制台的日志输出样式 -->
	<property name="CONSOLE_LOG_PATTERN"
		value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}" />

	<!-- 控制台输出 -->
	<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
		<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
			<level>INFO</level>
		</filter>
		<!-- 日志输出编码 -->
		<encoder>
			<pattern>${CONSOLE_LOG_PATTERN}</pattern>
			<charset>utf8</charset>
		</encoder>
	</appender>

	<!-- 为logstash输出的JSON格式的Appender -->
	<appender name="logstash"
		class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>${LOG_FILE}.json</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<!--日志文件输出的文件名 -->
			<fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>
			<!--日志文件保留天数 -->
			<MaxHistory>3</MaxHistory>
		</rollingPolicy>
		<!-- 日志输出编码 -->
		<encoder
			class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
			<providers>
				<timestamp>
					<timeZone>UTC</timeZone>
				</timestamp>
				<pattern>
					<pattern>
						{
						"severity": "%level",
						"service": "${springAppName:-}",
						"trace": "%X{X-B3-TraceId:-}",
						"span": "%X{X-B3-SpanId:-}",
						"exportable": "%X{X-Span-Export:-}",
						"pid": "${PID:-}",
						"thread": "%thread",
						"class": "%logger{40}",
						"rest": "%message"
						}
					</pattern>
				</pattern>
			</providers>
		</encoder>
	</appender>

	<!-- 日志输出级别 -->
	<root level="INFO">
		<appender-ref ref="console" />
		<appender-ref ref="logstash" />
	</root>
</configuration>

先启动eureka,再启动elk-trace1elk-trace2,浏览器访问http://localhost:7081/trace1验证结果。

我们发现在每个 server build 目录下有个 applicationName.json 文件,里面保存的就是 Json 格式的日志信息,例如:
{"@timestamp":"2017-10-19T15:27:48.353+00:00","severity":"INFO","service":"elk-trace1","trace":"a4ffc6b012f6ae8e","span":"a4ffc6b012f6ae8e","exportable":"false","pid":"8756","thread":"http-nio-7081-exec-10","class":"c.y.trace1.controller.Trace1Controller","rest":"======<call trace 1>======="}

现在已经有了Json日志数据,那么如何将这些数据送给Logstash呢?

 

按照前面2种方案设计,先看微服务与Logstash部署在一起的监听日志文件的方式。

在微服务节点安装个 logstash ,配置文件如下:
# For detail structure of this file
# Set: https://www.elastic.co/guide/en/logstash/current/configuration-file-structure.html
input {
  # For detail config for log4j as input, 
  # See: https://www.elastic.co/guide/en/logstash/current/plugins-inputs-log4j.html
  file {
    type => "server"
    path => "C:\spring\workspace\demo-elk-trace1\build\elk-trace1.json"
  }
}
filter {
  #Only matched data are send to output.
}
output {
  # For detail config for elasticsearch as output, 
  # See: https://www.elastic.co/guide/en/logstash/current/plugins-outputs-elasticsearch.html
  elasticsearch {
    action => "index"          #The operation on ES
    hosts  => "192.168.226.133:9200"   #ElasticSearch host, can be array.
    index  => "applog"         #The index to write data to.
  }
}
监控本服务的日志文件,并将其推送给 ElasticSearch 的接收地址。

再看第二种方案,独立部署Logstash

在一个空闲的逻辑节点上安装Logstash,配置文件如下:

# For detail structure of this file
# Set: https://www.elastic.co/guide/en/logstash/current/configuration-file-structure.html
input {
  # For detail config for log4j as input, 
  # See: https://www.elastic.co/guide/en/logstash/current/plugins-inputs-log4j.html
  tcp {
    mode => "server"
    host => "192.168.226.133"
    port => 9250
  }
}
filter {
  #Only matched data are send to output.
}
output {
  # For detail config for elasticsearch as output, 
  # See: https://www.elastic.co/guide/en/logstash/current/plugins-outputs-elasticsearch.html
  elasticsearch {
    action => "index"          #The operation on ES
    hosts  => "192.168.226.133:9200"   #ElasticSearch host, can be array.
    index  => "applog"         #The index to write data to.
  }
}

监听192.168.226.133:4567地址,将接收到的消息内容转发给elasticSearch接收地址。

代码需要做下改造,因为目前的代码只是将log日志信息的记录方式改为了Json格式,还不具备向Logstash的推送功能,修改logback-spring.xml,使用src/main/resources中的:

<?xml version="1.0" encoding="UTF-8"?>
<!--该日志将日志级别不同的log信息保存到不同的文件中 -->
<configuration>
	<include resource="org/springframework/boot/logging/logback/defaults.xml" />

	<springProperty scope="context" name="springAppName"
		source="spring.application.name" />

	<!-- 日志在工程中的输出位置 -->
	<property name="LOG_FILE" value="${BUILD_FOLDER:-build}/${springAppName}" />

	<!-- 控制台的日志输出样式 -->
	<property name="CONSOLE_LOG_PATTERN"
		value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}" />

	<!-- 控制台输出 -->
	<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
		<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
			<level>INFO</level>
		</filter>
		<!-- 日志输出编码 -->
		<encoder>
			<pattern>${CONSOLE_LOG_PATTERN}</pattern>
			<charset>utf8</charset>
		</encoder>
	</appender>

	<!-- 为logstash输出的JSON格式的Appender -->
	<appender name="logstash"
		class="net.logstash.logback.appender.LogstashTcpSocketAppender">
		<destination>192.168.226.133:9250</destination>
		<!-- 日志输出编码 -->
		<encoder
			class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
			<providers>
				<timestamp>
					<timeZone>UTC</timeZone>
				</timestamp>
				<pattern>
					<pattern>
						{
						"severity": "%level",
						"service": "${springAppName:-}",
						"trace": "%X{X-B3-TraceId:-}",
						"span": "%X{X-B3-SpanId:-}",
						"exportable": "%X{X-Span-Export:-}",
						"pid": "${PID:-}",
						"thread": "%thread",
						"class": "%logger{40}",
						"rest": "%message"
						}
					</pattern>
				</pattern>
			</providers>
		</encoder>
	</appender>

	<!-- 日志输出级别 -->
	<root level="INFO">
		<appender-ref ref="console" />
		<appender-ref ref="logstash" />
	</root>
</configuration>

浏览器请求http://localhost:7081/trace1

任务链请求到trace1trace1调用到trace2的服务,整个任务链的日志信息都经过logstash收集发送给了elasticsearch,搜索es可以获得本次任务链的所有节点的日志信息:


ELK更多的了解请参考 ELK-ElasticSearch+Logstash+Kibana


  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Table of Contents Title Page Copyright and Credits Mastering Spring Cloud Packt Upsell Why subscribe? PacktPub.com Contributors About the author About the reviewer Packt is searching for authors like you Preface Who this book is for What this book covers To get the most out of this book Download the example code files Conventions used Get in touch Reviews Introduction to Microservices The blessings of microservices Building microservices with Spring Framework Cloud-native development Learning the microservices architecture Understanding the need for service discovery Communication between services Failures and circuit breakers Summary Spring for Microservices Introducing Spring Boot Developing applications with Spring Boot Customizing configuration files Creating RESTful Web Services API Documentation Using Swagger 2 together with Spring Boot Testing API with Swagger UI Spring Boot Actuator features Application information Health information Metrics Developer tools Integrating application with database Building a sample application Running the application Summary Spring Cloud Overview Beginning with the basics Netflix OSS Service discovery with Eureka Routing with Zuul Load balancing with Ribbon Writing Java HTTP clients Latency and fault tolerance with Hystrix Configuration management with Archaius Discovery and distributed configuration An alternative – Consul Apache Zookeeper Miscellaneous projects Distributed tracing with Sleuth Messaging and integration Cloud platform support Other useful libraries Security Automated testing Cluster features Projects overview  Release trains Summary Service Discovery Running Eureka on the server side Enabling Eureka on the client side Deregistration on shutdown Using discovery client programmatically Advanced configuration settings Refreshing the registry Changing the instance identificator  Preferring the IP address Response cache Enabling secure communication between client and server Registering a secure service Eureka API Replication and high availability Architecture of the sample solution Building the example application Failover Zones Zones with a standalone server Building an example application Summary Distributed Configuration with Spring Cloud Config Introduction to HTTP API resources Native profile support Building a server-side application Building a client-side application Adding a Eureka Server Client-side bootstrap approaches Config Server discovery Repository backend types Filesystem backend Git backend Different protocols Using placeholders in URIs Building a server application Client-side configuration Multiple repositories Vault backend Getting started with Vault Integration with Spring Cloud Config Client-side configuration Additional features Fail on start and retry Secure client Reload configuration automatically Solution architecture Reload configuration with @RefreshScope Consuming events from a message broker Monitoring repository changes on a Config Server Simulating change events manually Testing locally with a GitLab instance  Summary Communication Between Microservices Different styles of communication  Synchronous communication with Spring Cloud Load balancing with Ribbon Enabling communication between microservices using the Ribbon client Static load balancing configuration Calling other services Using RestTemplate together with service discovery Building example application Using Feign client Support for different zones Enabling Feign for an application Building Feign interfaces Launching microservices Inheritance support Creating a client manually Client customization Summary Advanced Load Balancing and Circuit Breakers Load balancing rules The WeightedResponseTime rule Introducing Hoverfly for testing Testing the rule Customizing the Ribbon client The circuit breaker pattern with Hystrix Building an application with Hystrix Implementing Hystrix's commands Implementing fallback with cached data The tripping circuit breaker Monitoring latency and fault tolerance Exposing Hystrix's metrics stream Hystrix dashboard Building an application with the dashboard Monitoring metrics on the dashboard Aggregating Hystrix's streams with Turbine Enabling Turbine Enabling Turbine with streaming Failures and the circuit breaker pattern with Feign Retrying the connection with Ribbon Hystrix's support for Feign Summary Routing and Filtering with API Gateway Using Spring Cloud Netflix Zuul Building a gateway application Integration with service discovery Customizing route configuration Ignoring registered services Explicity set service name  Route definition with the Ribbon client Adding a prefix to the path Connection settings and timeouts Secure headers Management endpoints Providing Hystrix fallback Zuul filters Predefined filters Custom implementations Using Spring Cloud Gateway Enable Spring Cloud Gateway for a project Built-in predicates and filters Gateway for microservices Integration with service discovery Summary Distributed Logging and Tracing Best logging practices for microservices Logging with Spring Boot Centralizing logs with ELK Stack Setting up ELK Stack on the machine Integrating an application with ELK Stack Using LogstashTCPAppender Using AMQP appender and a message broker Spring Cloud Sleuth Integrating Sleuth with an application Searching events using Kibana Integrating Sleuth with Zipkin Running the Zipkin server Building the client application Analyze data with the Zipkin UI Integration via message broker Summary Additional Configuration and Discovery Features Using Spring Cloud Consul Running Consul agent Integration on the client side Service discovery Health check Zones Client settings customization Running in clustered mode Distributed configuration Managing properties in Consul Client customization Watching configuration changes Using Spring Cloud Zookeeper Running Zookeeper Service discovery Client implementation Zookeeper dependencies Distributed configuration Summary Message-Driven Microservices Learning about Spring Cloud Stream Building a messaging system Enabling Spring Cloud Stream Declaring and binding channels Customizing connectivity with the RabbitMQ broker Integration with other Spring Cloud projects The publish/subscribe model Running a sample system Scaling and grouping Running multiple instances Consumer groups Partitioning Configuration options Spring Cloud Stream properties Binding properties The consumer The producer The advanced programming model Producing messages Transformation Consuming messages conditionally Using Apache Kafka Running Kafka Customizing application settings Kafka Streams API support Configuration properties Multiple binders Summary Securing an API Enabling HTTPS for Spring Boot Secure discovery Registering a secure application Serving Eureka over HTTPS Keystore generation Configurating SSL for microservices and Eureka server Secure configuration server Encryption and decryption Configuring authentication for a client and a server Authorization with OAuth2 Introduction to OAuth2 Building an authorization server Client configuration Using the JDBC backend store Inter-service authorization Enabling SSO on the API gateway Summary Testing Java Microservices Testing strategies Testing Spring Boot applications Building the sample application Integration with the database Unit tests Component tests Running tests with an in-memory database Handling HTTP clients and service discovery Implementing sample tests Integration tests Categorizing tests Capturing HTTP traffic Contract tests Using Pact Consumer side Producer side Using Spring Cloud Contract Defining contracts and generating stubs Verifying a contract on the consumer side Scenarios Performance testing Gatling Enabling Gatling Defining the test scenario Running a test scenario Summary Docker Support Introducing Docker Installing Docker Commonly used Docker commands Running and stopping a container Listing and removing containers Pulling and pushing images Building an image Networking Creating a Docker image with microservices Dockerfiles Running containerized microservices Building an image using the Maven plugin Advanced Docker images Continuous Delivery Integrating Jenkins with Docker Building pipelines Working with Kubernetes Concepts and components Running Kubernetes locally via Minikube Deploying an application Maintaining a cluster Summary Spring Microservices on Cloud Platforms Pivotal Cloud Foundry Usage models Preparing the application Deploying the application Using CLI Binding to services Using the Maven plugin Maintenance Accessing deployment details Managing application life cycles Scaling Provisioning brokered services The Heroku platform Deployment methods Using the CLI Connecting to the GitHub repository Docker Container Registry Preparing an application Testing deployments Summary
资源名字:基于Springcloud+mysql的分布式架构网上商城设计与实现(源码+设计文档+部署说明+视频演示).zip 资源内容:项目全套源码+完整文档 源码说明: 全部项目源码都是经过测试校正后百分百成功运行。 基于Spring Cloud和MySQL的分布式架构网上商城是一个基于微服务架构的在线购物平台,具有以下主要特点: 技术栈:该系统采用了Java技术栈中的Spring Cloud框架,配合MySQL数据库,通过微服务拆分和分布式部署,具备高可用性和可伸缩性。 微服务架构:系统采用微服务架构,将不同的业务功能拆分为独立的服务,如用户服务、商品服务、订单服务、支付服务等,实现松耦合、可扩展的系统架构。 服务注册与发现:系统使用服务注册与发现机制,如Eureka、Consul等,实现服务的自动注册和发现,提供服务之间的通信和调用。 分布式数据一致性:系统通过分布式事务处理,保证多个服务之间的数据一致性,如使用分布式事务管理器(如Seata)或采用最终一致性方案(如异步消息队列)。 分布式缓存:系统使用分布式缓存,如Redis、Memcached等,提高系统的访问速度和性能,减轻数据库的压力。 异步消息处理:系统利用消息队列,如Kafka、RabbitMQ等,实现异步消息处理,如订单支付结果通知、库存变更等,提高系统的并发处理能力和可靠性。 安全认证与授权:系统实现用户的安全认证和授权,如使用Spring Security、OAuth2等,保护用户信息和资源的安全性。 监控与日志:系统使用监控工具和日志系统,如Spring Cloud Sleuth、Zipkin、ELK Stack等,实现对系统运行状态、性能和日志的监控和分析。 水平扩展与弹性伸缩:系统支持水平扩展和弹性伸缩,通过增加服务实例和负载均衡,实现系统的高并发和高可用性。 总之,基于Spring Cloud和MySQL的分布式架构网上商城具有商品信息展示,购物资讯、个人信息、购物车、用户管理、商品信息管理、商品分类管理等特点,为用户提供稳定、高效的在线购物体验。
要在 Spring Cloud集成 Log4j2 日志框架,可以通过添加以下依赖项来实现: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-sleuth</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-sleuth-zipkin</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-sleuth-stream</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zipkin</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bus-amqp</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-stream-rabbit</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-stream-binder-rabbit</artifactId> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>${log4j.version}</version> </dependency> ``` 然后在 `application.properties` 文件中添加以下配置: ``` spring.cloud.stream.bindings.output.destination=myTopic spring.sleuth.sampler.probability=1.0 logging.level.org.springframework.cloud.stream=DEBUG logging.level.org.springframework.integration=DEBUG logging.level.org.springframework.amqp=DEBUG spring.cloud.stream.bindings.input.destination=myTopic spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest spring.zipkin.baseUrl=http://localhost:9411 ``` 这里的配置包括了日志的级别以及 Sleuth 和 Zipkin 的配置。最后,可以使用以下代码来测试日志输出: ```java @Slf4j @RestController @RequestMapping("/api") public class DemoController { @GetMapping("/test") public String test() { log.debug("This is a debug message"); log.info("This is an info message"); log.warn("This is a warning message"); log.error("This is an error message"); return "Test"; } } ``` 如果一切顺利,你应该能够在控制台看到输出的日志信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值