Show List

Spring Boot with Splunk Integration

To create a Spring Boot application that sends logs to Splunk, you can use the Splunk HTTP Event Collector (HEC) to ingest the logs. Here's a basic example of how you can set up a Spring Boot application to send logs to Splunk using the HEC:

  1. Add Dependencies: Start by adding the necessary dependencies to your pom.xml file:

<dependencies> <!-- Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Logback for logging --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </dependency> <!-- HTTP Client --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> </dependencies>
  1. Configure Logback: Configure Logback to send logs to Splunk by adding the appropriate appender. Here's an example logback.xml configuration:

<configuration> <appender name="SPLUNK" class="ch.qos.logback.classic.net.HttpAppender"> <url>http://splunk-server:8088/services/collector</url> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> </layout> <encoder> <pattern>%msg</pattern> </encoder> </appender> <root level="INFO"> <appender-ref ref="SPLUNK" /> </root> </configuration>

Replace http://splunk-server:8088/services/collector with your Splunk HEC endpoint.

  1. Create a Spring Boot Application: Create a simple Spring Boot application with a REST controller to generate some logs.

import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class SplunkLoggerApplication { private static final Logger logger = LoggerFactory.getLogger(SplunkLoggerApplication.class); public static void main(String[] args) { SpringApplication.run(SplunkLoggerApplication.class, args); } @GetMapping("/") public String hello() { logger.info("Hello, Splunk!"); return "Hello, Splunk!"; } }
  1. Run the Application: Run the Spring Boot application. You should see logs generated by the application being sent to Splunk via the HTTP Event Collector.

This is a basic setup to send logs to Splunk from a Spring Boot application. Depending on your requirements, you may need to customize the configuration and logging levels. Additionally, you might want to handle error scenarios and add more sophisticated logging features.


    Leave a Comment


  • captcha text