Springboot整合Kafka、Logstash实现日志异步

Springboot整合Kafka、Logstash实现日志异步_第1张图片

前言

企业开发中,一个应用会有多个测试环境,于是会有一个专门的服务器做日志收集,那就需要保存日志和应用隔离,这里就牵涉到异步存写日志的问题,异步消息队列选取kafka,高性能,日志消息消费我们使用logstash。这里也可以都使用elk(土豪请绕过)。

Kafka的搭建

习惯使用docker-compose启动,脚本如下:

version: '2'
services:
  zookeeper:
    image: wurstmeister/zookeeper   ## 镜像
    ports:
      - "2181:2181"                 ## 对外暴露的端口号
  kafka:
    image: wurstmeister/kafka       ## 镜像
    volumes:
        - /etc/localtime:/etc/localtime ## 挂载位置(kafka镜像和宿主机器之间时间保持一直)
    ports:
      - "9092:9092"
    environment:
      KAFKA_ADVERTISED_HOST_NAME:    ## 修改:宿主机IP
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181       ## kafka运行是基于zookeeper的
  kafka-manager:
    image: sheepkiller/kafka-manager                ## 镜像:开源的web管理kafka集群的界面
    environment:
        ZK_HOSTS:                    ## 修改:宿主机IP
    ports:
      - "9000:9000"

docker-compose up -d 后台方式启动
docker-compose stop 关闭
docker-compose ps 查看有哪些应用
docker-compose build 构建镜像

Logstash的搭建

同样也是用docker-compose启动,脚本如下:

docker-compose.yml->

version: "3"
services:
    logstash-1:
        image: logstash:7.0.0
        container_name: logstash
        volumes:
            - ${LOGSTASH_CONFIG_DIR}/logstash.conf:/usr/share/logstash/pipeline/logstash.conf:rw
            - ${LOGSTASH_CONFIG_DIR}/logstash.yml:/usr/share/logstash/config/logstash.yml:rw
        network_mode: "host"

logstash.confi

input {
  kafka {
    bootstrap_servers => "IP:9092"
    topics => ["abklog_topic"]
    group_id => "abklog_topic"
  }
}


output {
  file {
    file_mode => 0777
    dir_mode => 0777
    path => "/path/to/%{+yyyy-MM-dd-HH}/%{host}.log"
  }
  stdout {
    codec => rubydebug
  }
}

logstash.yml


# set now host ip to http.host
http.host: 192.168.56.121
# set the es-tribe-node host. let logstash monitor the es.
#xpack.monitoring.elasticsearch.hosts:
#- http://10.2.114.110:9204
# enable or disable the logstash monitoring the es.
#xpack.monitoring.enabled: true

Java日志配置

在你改好的springboot工程中整好,加入这个依赖。

 		<!-- https://mvnrepository.com/artifact/com.github.danielwegener/logback-kafka-appender -->
        <dependency>
            <groupId>com.github.danielwegener</groupId>
            <artifactId>logback-kafka-appender</artifactId>
            <version>0.2.0-RC2</version>
        </dependency>

logback.xml配置



	
	
		
		
		
		
		
			
			
				%boldYellow(${module}) | %d | %highlight(%-5level)| %cyan(%logger{15}) - %msg %n
			
		
		
		
			
				${module} | %d | %-5level| %logger{15} - %msg
			
			abklog_topic
			
			

			
			

			
			

			
			
			
			bootstrap.servers=${bootstrapServers}

			
			

		
		
		
		
			
		
		
			
		
	

记得将kafka的ip换成你真实的ip

你可能感兴趣的:(微服务,kafka,logback,spring,boot)