Complete Guide to Setting Up ELK Stack with Kafka, Redis, Beats, and Spring Boot for Microservices Logging

Architecture diagram:

Components Breakdown:

  1. Microservices 1, 2, and 3:

    • These are the core applications responsible for generating logs.
  2. Logstash:

    • Acts as a central log processor. It collects logs from the microservices, transforms them into a common format (usually JSON), and sends them to Elasticsearch.
  3. Elasticsearch:

    • A powerful search engine that stores and indexes the logs received from Logstash. It allows for fast retrieval and analysis of log data.
  4. Kafka:

    • A distributed streaming platform used to buffer and distribute logs from the microservices to Logstash. Kafka ensures reliability and fault tolerance in log handling.
  5. Redis:

    • An in-memory data store used for caching, session management, and other purposes. Redis can help improve the performance and scalability of the application.
  6. Beats:

    • A lightweight data shipper that can forward logs from the microservices to Logstash or Kafka. Beats is typically used for collecting logs from application files or other sources.
  7. Kibana:

    • A data visualization and exploration tool that allows users to query, visualize, and analyze the logs stored in Elasticsearch. Kibana provides an intuitive interface for monitoring and troubleshooting the logs.

Overall Flow:

  1. Log Generation:

    • The microservices generate application logs.
  2. Log Collection:

    • Beats or Kafka collects logs from the microservices and sends them to Logstash.
  3. Log Processing:

    • Logstash receives logs from Beats or Kafka, transforms them, and sends them to Elasticsearch.
  4. Log Storage:

    • Elasticsearch stores and indexes the logs, enabling fast search and retrieval.
  5. Log Analysis:

    • Kibana provides a user interface for querying, visualizing, and analyzing the logs stored in Elasticsearch. This allows users to gain insights and monitor the health of their microservices.

Additional Notes:

  • The use of Kafka enhances scalability and fault tolerance by decoupling log producers (microservices) from log consumers (Logstash, Elasticsearch). This makes the system more resilient and capable of handling large volumes of log data.

  • Redis can be used for caching, session management, and other performance-enhancing purposes. It can reduce latency by storing frequently accessed data in memory.


To set up a complete logging pipeline for a microservices architecture with Elasticsearch, Logstash, Kibana (ELK) stack, Kafka, Redis, Beats, and Spring Boot Microservices (Microservices 1, 2, and 3), follow the detailed steps below.

1. Install and Configure Elasticsearch

Install Elasticsearch:

  • Download and install Elasticsearch from the official website.
  • Extract and start the Elasticsearch service:
    bin/elasticsearch

Configure Elasticsearch:

  • Edit elasticsearch.yml to bind the network and configure cluster settings (e.g., network.host, cluster.name, etc.):
    network.host: 0.0.0.0
    cluster.name: "log-cluster"

2. Install and Configure Logstash

Install Logstash:

  • Download and install Logstash from Logstash Download Page.
  • Install Kafka and Redis plugins for Logstash:
    bin/logstash-plugin install logstash-input-kafka
    bin/logstash-plugin install logstash-output-elasticsearch

Create Logstash Configuration (logstash.conf):

  • Define input, filter, and output configuration in the Logstash configuration file:
    input {
      kafka {
        bootstrap_servers => "localhost:9092"
        topics => ["microservices-logs"]
      }
    }
    
    filter {
      json {
        source => "message"
      }
    }
    
    output {
      elasticsearch {
        hosts => ["http://localhost:9200"]
        index => "microservices-logs-%{+YYYY.MM.dd}"
      }
    }
  • This configuration will collect logs from Kafka and push them to Elasticsearch.

Start Logstash:

bin/logstash -f logstash.conf

3. Install and Configure Kibana

Install Kibana:

Configure Kibana:

  • Edit the kibana.yml configuration file to set the Elasticsearch host:
    server.host: "0.0.0.0"
    elasticsearch.hosts: ["http://localhost:9200"]

Start Kibana:

bin/kibana

4. Install and Configure Kafka

Install Kafka:

  • Download and install Kafka from Kafka Download Page.

  • Start Zookeeper (Kafka depends on Zookeeper):

    bin/zookeeper-server-start.sh config/zookeeper.properties
  • Start Kafka:

    bin/kafka-server-start.sh config/server.properties

Create Kafka Topic:

bin/kafka-topics.sh --create --topic microservices-logs --bootstrap-server localhost:9092 --partitions 1 --replication-factor 1

5. Install and Configure Redis (Optional for Buffering)

Install Redis:

Use Redis as a Buffer:

  • Redis can be used to buffer logs before sending them to Kafka or Elasticsearch. Configure your Spring Boot microservices to send logs to Redis first if needed.

6. Install and Configure Beats (Filebeat)

Install Filebeat:

  • Download and install Filebeat from Filebeat Download Page.
  • Configure Filebeat to monitor the log files of Spring Boot microservices and forward them to Logstash.

Configure Filebeat: Edit the filebeat.yml file:

filebeat.inputs:
- type: log
  enabled: true
  paths:
    - /path/to/microservices-logs/*.log

output.logstash:
  hosts: ["localhost:5044"]

Start Filebeat:

sudo filebeat -e

7. Configure Spring Boot Microservices

For each Spring Boot microservice (Microservice 1, 2, and 3), you need to configure logging so that logs are sent to Kafka or directly to Redis.

Add Dependencies to pom.xml:

<dependency>
    <groupId>org.springframework.kafka</groupId>
    <artifactId>spring-kafka</artifactId>
</dependency>

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

Configure Logback (or Log4j2) to Send Logs to Kafka:

Example for logback-spring.xml:

<appender name="KAFKA" class="org.apache.kafka.log4jappender.KafkaAppender">
    <param name="kafka.topic" value="microservices-logs"/>
    <param name="kafka.bootstrap.servers" value="localhost:9092"/>
    <param name="layout" value="org.apache.log4j.PatternLayout"/>
    <param name="Pattern" value="%d{ISO8601} [%-5p] %c{1}:%L - %m%n"/>
</appender>

<root level="info">
    <appender-ref ref="KAFKA"/>
</root>

In this configuration, log messages from Spring Boot microservices will be sent to Kafka in the microservices-logs topic.

8. Monitor Logs in Kibana

Once everything is set up, you can use Kibana to monitor the logs. Kibana will show logs indexed by Elasticsearch, and you can query logs using the search bar and create visualizations or dashboards.

  1. Go to http://localhost:5601 to access the Kibana UI.
  2. Create an index pattern for microservices-logs-*.
  3. Go to the "Discover" section to view incoming logs in real-time.

9. Test and Verify the Pipeline

  • Start your Spring Boot microservices (1, 2, and 3).
  • Generate some log data by making requests to your microservices.
  • Check if logs are visible in Kibana in real-time.
  • If using Filebeat, verify the log files are being sent to Logstash and processed correctly.
  • Ensure Kafka is receiving logs and Logstash is forwarding them to Elasticsearch.

10. Optional Enhancements

  • Kafka Connect: If you have other data sources, use Kafka Connect to connect other systems with Kafka.
  • Redis: Use Redis for buffering logs or for caching log data before processing.
  • Monitoring & Alerts: Set up monitoring and alerting in Kibana to notify you about certain log events (e.g., errors).

Summary of Components:

  1. Elasticsearch: Stores and indexes logs.
  2. Logstash: Processes logs from Kafka, formats them, and forwards them to Elasticsearch.
  3. Kibana: Visualizes and analyzes logs in real-time.
  4. Kafka: Acts as the central log aggregator.
  5. Redis: Optionally used for buffering or caching logs.
  6. Beats (Filebeat): Collects and forwards log files from microservices.
  7. Spring Boot Microservices: Generate and send logs to Kafka or Redis.

This setup ensures that logs from your Spring Boot microservices are captured, processed, and displayed effectively for monitoring and troubleshooting.

When to Use This Architecture

  1. High Traffic Microservices: Ideal for large systems with many microservices generating high log volumes.

  2. Real-time Monitoring: Needed for real-time log analysis and quick issue detection.

  3. Scalable Infrastructure: Useful when the system grows and requires scalable logging.

  4. Distributed Systems: Aggregates logs from multiple microservices for easier debugging.

  5. Structured Logs: Efficient when logs are in structured formats (e.g., JSON) that need fast querying.

  6. Improved Debugging: Helps trace requests across services for distributed debugging.

When NOT to Use This Architecture

  1. Small Applications: Overkill for small or monolithic apps.

  2. Low Log Volume: Unnecessary for applications with minimal log traffic.

  3. Short-term Projects: Not needed for prototypes or projects without scalability demands.

  4. Limited Resources: Too resource-intensive for teams with limited capacity.

  5. Simple Debugging: Unnecessary for apps with basic logging needs.


Buy Now – Unlock Your Microservices Mastery for Only $9!

Get your copy now for just $9! and start building resilient and scalable microservices with the help of Microservices with Spring Boot 3 and Spring Cloud.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete