DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • A Systematic Approach for Java Software Upgrades
  • Building a Simple RAG Application With Java and Quarkus
  • Dust Actors and Large Language Models: An Application
  • Five Java Developer Must-Haves for Ultra-Fast Startup Solutions

Trending

  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 2
  • Using Java Stream Gatherers To Improve Stateful Operations
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  • Agile’s Quarter-Century Crisis
  1. DZone
  2. Coding
  3. Java
  4. End to End Distributed Logging Traceability With Custom Context

End to End Distributed Logging Traceability With Custom Context

This article helps a simple End to End Logging Traceability using Open Source Technologies such as SpringBoot, Sleuth, and more!

By 
Arumugam Maruthanayagam user avatar
Arumugam Maruthanayagam
·
May. 04, 20 · Analysis
Likes (6)
Comment
Save
Tweet
Share
7.7K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

This article helps a simple End to End Logging Traceability using Open Source Technologies such as (SpringBoot, Sleuth, MDC, LogStash, ElasticSearch, and Kibana).

Problem Statement

In the Distributed Application world, their many application participates for a given customer business process. There are difficulties to trace the log details when any problem occurs for these distributed applications. Each development team uses its logging pattern and method or APIs (Apache Logger, ALF4J, Log4j or Log4j2, Java Util Logging, Logback.. ).

In the real production or Integration Environment, each of the module developers struggles to debug the problem since there is no Unique TraceId across the multiple Applications. Also, developers might struggle to identify the Functional Context information since which is not shared across multiple Applications.

Solution Approach

Option 1: You can make use of the built-in Springboot Sleuth which is a simple and more efficient way to create a TraceId and spanId. TraceId will be propagated to all the Microservices/Rest Components/Servlet Applications.

Service One

To view the Distributed Logs into a centralized Dashboard view, you can use even Zipkin or Kibana or any Visual Tools.

I have chosen Kibana which is easy to use, better performance using ElasticSearch, a more reliable Logstash pipeline, and much better usability.

Let's start with our solution

Prerequisites

Java 1.8 or 11 or 13

Any Java IDE (IntelliJ / Eclipse / ..)

Install LogStash: https://www.elastic.co/guide/en/logstash/current/installing-logstash.html

Install Elastic Search: https://www.elastic.co/guide/en/elasticsearch/reference/current/install-elasticsearch.html

Install Kibana: https://www.elastic.co/guide/en/kibana/current/install.html

Create 3 Springboot Projects using https://start.spring.io

Project 1: CoreAppOneService

Java
 




x
11
9


 
1
src/main/resources/application.properties
2
server.port=8080
3
src/main/resources/bootstrap.yml
4
spring:
5
application:
6
name: coreappone



Src/main/resources/logback-spring.xml

Java
 




xxxxxxxxxx
1
80


 
1
<?xml version="1.0" encoding="UTF-8"?>
2
<configuration>
3
  <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
4
  
5
  <springProperty scope="context" name="springAppName" source="spring.application.name"/>
6
  <!-- Example for logging into the build folder of your project -->
7
  <p>
8
 
          
9
  <!-- You can override this to have a custom pattern -->
10
  <property name="CONSOLE_LOG_PATTERN"
11
    value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %X{context.userId} %X{context.moduleId} %X{context.caseId} %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
12
 
          
13
  <!-- Appender to log to console -->
14
  <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
15
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
16
      <!-- Minimum logging level to be presented in the console logs-->
17
      <level>DEBUG</level>
18
    </filter>
19
    <encoder>
20
      <p>${CONSOLE_LOG_PATTERN}</pattern>
21
      <charset>utf8</charset>
22
    </encoder>
23
  </appender>
24
 
          
25
  <!-- Appender to log to file -->
26
  <appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
27
    <file>${LOG_FILE}</file>
28
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
29
      <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
30
      <maxHistory>7</maxHistory>
31
    </rollingPolicy>
32
    <encoder>
33
      <p>${CONSOLE_LOG_PATTERN}</pattern>
34
      <charset>utf8</charset>
35
    </encoder>
36
  </appender>
37
  
38
  <!-- Appender to log to file in a JSON format -->
39
  <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">
40
    <file>${LOG_FILE}.json</file>
41
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
42
      <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>
43
      <maxHistory>7</maxHistory>
44
    </rollingPolicy>
45
    <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
46
      <p>
47
        <timestamp>
48
          <timeZone>UTC</timeZone>
49
        </timestamp>
50
        <p>
51
          <p>
52
            {
53
            "severity": "%level",
54
            "service": "${springAppName:-}",
55
            "trace": "%X{X-B3-TraceId:-}",
56
            "span": "%X{X-B3-SpanId:-}",
57
            "parent": "%X{X-B3-ParentSpanId:-}",
58
            "exportable": "%X{X-Span-Export:-}",
59
            "pid": "${PID:-}",
60
            "thread": "%thread",
61
            "pvai.userId": "%X{context.userId:-}",
62
            "pvai.moduleId": "%X{context.moduleId:-}",
63
            "pvai.caseId": "%X{context.caseId:-}",
64
            "class": "%logger{40}",
65
            "rest": "%message"
66
            }
67
          </pattern>
68
        </pattern>
69
      </providers>
70
    </encoder>
71
  </appender>
72
  
73
  <root level="INFO">
74
    <appender-ref ref="console"/>
75
    <!-- uncomment this to have also JSON logs -->
76
    <appender-ref ref="logstash"/>
77
    <appender-ref ref="flatfile"/>
78
  </root>
79
</configuration>
80
 
          



src/main/java/com.dzone.sample.logging

Java
 




xxxxxxxxxx
1
39


 
1
package com.dzone.sample.logging;
2
 
          
3
import java.io.IOException;
4
import javax.servlet.FilterChain;
5
import javax.servlet.ServletException;
6
import javax.servlet.ServletRequest;
7
import javax.servlet.ServletResponse;
8
import org.slf4j.Logger;
9
import org.slf4j.LoggerFactory;
10
import org.slf4j.MDC;
11
import org.springframework.stereotype.Component;
12
import org.springframework.web.filter.GenericFilterBean;
13
 
          
14
@Component
15
public class CoreApp1MDCFilter extends GenericFilterBean {
16
 
          
17
  private static final Logger logger = LoggerFactory.getLogger(CoreApp1MDCFilter.class);
18
 
          
19
  @Override
20
  public void destroy() {
21
  }
22
 
          
23
  @Override
24
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
25
      FilterChain filterChain) throws IOException, ServletException {
26
 
          
27
    MDC.put("context.userId", "amarutha");
28
    MDC.put("context.moduleId", "CoreApp1");
29
    MDC.put("context.caseId", "Case001");
30
 
          
31
    logger.trace("A TRACE Message");
32
    logger.debug("A DEBUG Message");
33
    logger.info("An INFO Message");
34
    logger.warn("A WARN Message");
35
    logger.error("An ERROR Message");
36
    filterChain.doFilter(servletRequest, servletResponse);
37
  }
38
}
39
 
          



src/main/java/com.dzone.sample.logging

Java
 




xxxxxxxxxx
1
57


 
1
package com.dzone.sample.logging;
2
 
          
3
import org.slf4j.Logger;
4
import org.slf4j.LoggerFactory;
5
import org.slf4j.MDC;
6
import org.springframework.boot.SpringApplication;
7
import org.springframework.boot.autoconfigure.SpringBootApplication;
8
import org.springframework.boot.devtools.remote.client.HttpHeaderInterceptor;
9
import org.springframework.context.annotation.Bean;
10
import org.springframework.http.MediaType;
11
import org.springframework.http.client.ClientHttpRequestInterceptor;
12
import org.springframework.util.CollectionUtils;
13
import org.springframework.web.bind.annotation.RequestMapping;
14
import org.springframework.web.bind.annotation.RestController;
15
import org.springframework.web.client.RestTemplate;
16
 
          
17
import java.util.ArrayList;
18
import java.util.List;
19
 
          
20
 
          
21
@RestController
22
@SpringBootApplication
23
public class LoggingCoreApplicationOne {
24
 
          
25
  private static final Logger logger = LoggerFactory.getLogger(LoggingCoreApplicationOne.class);
26
 
          
27
  public static void main(String[] args) {
28
    SpringApplication.run(LoggingCoreApplicationOne.class, args);
29
  }
30
 
          
31
  @Bean
32
  public RestTemplate getRestTemplate() {
33
    return new RestTemplate();
34
  }
35
 
          
36
  @RequestMapping("/coreapp1")
37
  public String callCoreApp2Service() throws Exception {
38
    logger.trace("A TRACE Message");
39
    logger.debug("A DEBUG Message");
40
    logger.info("An INFO Message");
41
    logger.warn("A WARN Message");
42
    logger.error("An ERROR Message");
43
 
          
44
    final RestTemplate restTemplate = getRestTemplate();
45
    List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
46
    if (CollectionUtils.isEmpty(interceptors)) {
47
      interceptors = new ArrayList<>();
48
    }
49
 
          
50
    interceptors.add(new HttpHeaderInterceptor("pvai.userId", MDC.get("pvai.userId")));
51
    interceptors.add(new HttpHeaderInterceptor("pvai.caseId", MDC.get("pvai.caseId")));
52
 
          
53
    restTemplate.setInterceptors(interceptors);
54
    return "This is CoreAppOne Service " + restTemplate
55
        .getForObject("http://localhost:8081/coreapp2", String.class);
56
  }
57
}



pom.xml

Java
 




xxxxxxxxxx
1
62


 
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0"
3
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
5
  <modelVersion>4.0.0</modelVersion>
6
  <p>
7
    <groupId>org.springframework.boot</groupId>
8
    <artifactId>spring-boot-starter-parent</artifactId>
9
    <version>2.2.3.RELEASE</version>
10
    <relativePath/> <!-- lookup parent from repository -->
11
  </parent>
12
  <groupId>com.dzone.sample.logging</groupId>
13
  <artifactId>Logging_CoreAppOne</artifactId>
14
  <version>0.0.1-SNAPSHOT</version>
15
  <name>Logging_CoreAppOne</name>
16
  <description>Demo project for Spring Boot</description>
17
 
          
18
  <p>
19
    <java.version>1.8</java.version>
20
  </properties>
21
 
          
22
 
          
23
  <dependencies>
24
    <dependency>
25
      <groupId>org.springframework.cloud</groupId>
26
      <artifactId>spring-cloud-starter-sleuth</artifactId>
27
      <version>2.2.1.RELEASE</version>
28
    </dependency>
29
    <dependency>
30
      <groupId>org.springframework.boot</groupId>
31
      <artifactId>spring-boot-starter-web</artifactId>
32
    </dependency>
33
    <dependency>
34
      <groupId>org.springframework.boot</groupId>
35
      <artifactId>spring-boot-starter-test</artifactId>
36
      <scope>test</scope>
37
    </dependency>
38
    <dependency>
39
      <groupId>net.logstash.logback</groupId>
40
      <artifactId>logstash-logback-encoder</artifactId>
41
      <version>6.3</version>
42
    </dependency>
43
    <dependency>
44
      <groupId>org.slf4j</groupId>
45
      <artifactId>log4j-over-slf4j</artifactId>
46
    </dependency>
47
    <dependency>
48
      <groupId>org.springframework.boot</groupId>
49
      <artifactId>spring-boot-devtools</artifactId>
50
    </dependency>
51
  </dependencies>
52
 
          
53
  <build>
54
    <p>
55
      <p>
56
        <groupId>org.springframework.boot</groupId>
57
        <artifactId>spring-boot-maven-plugin</artifactId>
58
      </plugin>
59
    </plugins>
60
  </build>
61
 
          
62
</project>



Project 2: CoreAppTwoService

Java
 




xxxxxxxxxx
1
11
9


 
1
src/main/resources/application.properties
2
server.port=8081
3
src/main/resources/bootstrap.yml
4
spring:
5
application:
6
name: coreapptwo



src/main/resources/logback-spring.xml

Java
 




xxxxxxxxxx
1
79


 
1
<?xml version="1.0" encoding="UTF-8"?>
2
<configuration>
3
  <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
4
  
5
  <springProperty scope="context" name="springAppName" source="spring.application.name"/>
6
  <!-- Example for logging into the build folder of your project -->
7
  <p>
8
 
          
9
  <!-- You can override this to have a custom pattern -->
10
  <property name="CONSOLE_LOG_PATTERN"
11
    value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %X{context.userId} %X{contet.moduleId} %X{context.caseId} %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
12
 
          
13
  <!-- Appender to log to console -->
14
  <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
15
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
16
      <!-- Minimum logging level to be presented in the console logs-->
17
      <level>DEBUG</level>
18
    </filter>
19
    <encoder>
20
      <p>${CONSOLE_LOG_PATTERN}</pattern>
21
      <charset>utf8</charset>
22
    </encoder>
23
  </appender>
24
 
          
25
  <!-- Appender to log to file -->
26
  <appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
27
    <file>${LOG_FILE}</file>
28
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
29
      <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
30
      <maxHistory>7</maxHistory>
31
    </rollingPolicy>
32
    <encoder>
33
      <p>${CONSOLE_LOG_PATTERN}</pattern>
34
      <charset>utf8</charset>
35
    </encoder>
36
  </appender>
37
  
38
  <!-- Appender to log to file in a JSON format -->
39
  <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">
40
    <file>${LOG_FILE}.json</file>
41
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
42
      <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>
43
      <maxHistory>7</maxHistory>
44
    </rollingPolicy>
45
    <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
46
      <p>
47
        <timestamp>
48
          <timeZone>UTC</timeZone>
49
        </timestamp>
50
        <p>
51
          <p>
52
            {
53
            "severity": "%level",
54
            "service": "${springAppName:-}",
55
            "trace": "%X{X-B3-TraceId:-}",
56
            "span": "%X{X-B3-SpanId:-}",
57
            "parent": "%X{X-B3-ParentSpanId:-}",
58
            "exportable": "%X{X-Span-Export:-}",
59
            "pid": "${PID:-}",
60
            "thread": "%thread",
61
            "pvai.userId": "%X{context.userId:-}",
62
            "pvai.moduleId": "%X{context.moduleId:-}",
63
            "pvai.caseId": "%X{context.caseId:-}",
64
            "class": "%logger{40}",
65
            "rest": "%message"
66
            }
67
          </pattern>
68
        </pattern>
69
      </providers>
70
    </encoder>
71
  </appender>
72
  
73
  <root level="INFO">
74
    <appender-ref ref="console"/>
75
    <!-- uncomment this to have also JSON logs -->
76
    <appender-ref ref="logstash"/>
77
    <appender-ref ref="flatfile"/>
78
  </root>
79
</configuration>



src/main/java/com.dzone.sample.logging

Java
 




xxxxxxxxxx
1
40


 
1
package com.dzone.sample.logging;
2
 
          
3
import java.io.IOException;
4
import javax.servlet.FilterChain;
5
import javax.servlet.ServletException;
6
import javax.servlet.ServletRequest;
7
import javax.servlet.ServletResponse;
8
import javax.servlet.http.HttpServletRequest;
9
import org.slf4j.Logger;
10
import org.slf4j.LoggerFactory;
11
import org.slf4j.MDC;
12
import org.springframework.stereotype.Component;
13
import org.springframework.web.filter.GenericFilterBean;
14
 
          
15
@Component
16
public class CoreAppTwoMDCFilter extends GenericFilterBean {
17
 
          
18
  private static final Logger logger = LoggerFactory.getLogger(CoreAppTwoMDCFilter.class);
19
 
          
20
  @Override
21
  public void destroy() {
22
  }
23
 
          
24
  @Override
25
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
26
      FilterChain filterChain) throws IOException, ServletException {
27
 
          
28
    MDC.put("context.userId", ((HttpServletRequest) servletRequest).getHeader("context.userId"));
29
    MDC.put("context.moduleId", "CoreAppTwoService");
30
    MDC.put("context.caseId", ((HttpServletRequest) servletRequest).getHeader("context.caseId"));
31
 
          
32
    logger.trace("A TRACE Message");
33
    logger.debug("A DEBUG Message");
34
    logger.info("An INFO Message" );
35
    logger.warn("A WARN Message" );
36
    logger.error("An ERROR Message");
37
    filterChain.doFilter(servletRequest, servletResponse);
38
  }
39
}
40
 
          



src/main/java/com.dzone.sample.logging

Java
 




xxxxxxxxxx
1
57


 
1
package com.dzone.sample.logging;
2
 
          
3
import org.slf4j.Logger;
4
import org.slf4j.LoggerFactory;
5
import org.slf4j.MDC;
6
import org.springframework.boot.SpringApplication;
7
import org.springframework.boot.autoconfigure.SpringBootApplication;
8
import org.springframework.boot.devtools.remote.client.HttpHeaderInterceptor;
9
import org.springframework.context.annotation.Bean;
10
import org.springframework.http.MediaType;
11
import org.springframework.http.client.ClientHttpRequestInterceptor;
12
import org.springframework.util.CollectionUtils;
13
import org.springframework.web.bind.annotation.RequestMapping;
14
import org.springframework.web.bind.annotation.RestController;
15
import org.springframework.web.client.RestTemplate;
16
 
          
17
import java.util.ArrayList;
18
import java.util.List;
19
 
          
20
@RestController
21
@SpringBootApplication
22
public class LoggingCoreApplicationTwo {
23
 
          
24
  private static final Logger logger = LoggerFactory.getLogger(LoggingCoreApplicationTwo.class);
25
 
          
26
  public static void main(String[] args) {
27
    SpringApplication.run(LoggingApplicationTwo.class, args);
28
  }
29
 
          
30
  @Bean
31
  public RestTemplate getRestTemplate() {
32
    return new RestTemplate();
33
  }
34
 
          
35
  @RequestMapping("/coreapp3")
36
  public String callCoreAppThreeService() throws Exception {
37
    logger.trace("A TRACE Message");
38
    logger.debug("A DEBUG Message");
39
    logger.info("An INFO Message");
40
    logger.warn("A WARN Message");
41
    logger.error("An ERROR Message");
42
 
          
43
    final RestTemplate restTemplate = getRestTemplate();
44
    List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
45
    if (CollectionUtils.isEmpty(interceptors)) {
46
      interceptors = new ArrayList<>();
47
    }
48
 
          
49
    interceptors.add(new HttpHeaderInterceptor("context.userId", MDC.get("context.userId")));
50
    interceptors.add(new HttpHeaderInterceptor("context.caseId", MDC.get("context.caseId")));
51
 
          
52
    restTemplate.setInterceptors(interceptors);
53
    return "This is CoreAppTwo Service " + restTemplate
54
        .getForObject("http://localhost:8082/coreapp3", String.class);
55
  }
56
}
57
 
          



Project 3: CoreAppThreeService

Java
 




xxxxxxxxxx
1
11
9


 
1
src/main/resources/application.properties
2
server.port=8082
3
src/main/resources/bootstrap.yml
4
spring:
5
application:
6
name: coreappthree



src/main/resources/logback-spring.xml

Java
 




x
80


 
1
<?xml version="1.0" encoding="UTF-8"?>
2
<configuration>
3
  <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
4
  
5
  <springProperty scope="context" name="springAppName" source="spring.application.name"/>
6
  <!-- Example for logging into the build folder of your project -->
7
  <p>
8
 
          
9
  <!-- You can override this to have a custom pattern -->
10
  <property name="CONSOLE_LOG_PATTERN"
11
    value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %X{context.userId} %X{context.moduleId} %X{context.caseId} %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
12
 
          
13
  <!-- Appender to log to console -->
14
  <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
15
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
16
      <!-- Minimum logging level to be presented in the console logs-->
17
      <level>DEBUG</level>
18
    </filter>
19
    <encoder>
20
      <p>${CONSOLE_LOG_PATTERN}</pattern>
21
      <charset>utf8</charset>
22
    </encoder>
23
  </appender>
24
 
          
25
  <!-- Appender to log to file -->
26
  <appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
27
    <file>${LOG_FILE}</file>
28
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
29
      <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
30
      <maxHistory>7</maxHistory>
31
    </rollingPolicy>
32
    <encoder>
33
      <p>${CONSOLE_LOG_PATTERN}</pattern>
34
      <charset>utf8</charset>
35
    </encoder>
36
  </appender>
37
  
38
  <!-- Appender to log to file in a JSON format -->
39
  <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">
40
    <file>${LOG_FILE}.json</file>
41
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
42
      <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>
43
      <maxHistory>7</maxHistory>
44
    </rollingPolicy>
45
    <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
46
      <p>
47
        <timestamp>
48
          <timeZone>UTC</timeZone>
49
        </timestamp>
50
        <p>
51
          <p>
52
            {
53
            "severity": "%level",
54
            "service": "${springAppName:-}",
55
            "trace": "%X{X-B3-TraceId:-}",
56
            "span": "%X{X-B3-SpanId:-}",
57
            "parent": "%X{X-B3-ParentSpanId:-}",
58
            "exportable": "%X{X-Span-Export:-}",
59
            "pid": "${PID:-}",
60
            "thread": "%thread",
61
            "pvai.userId": "%X{context.userId:-}",
62
            "pvai.moduleId": "%X{context.moduleId:-}",
63
            "pvai.caseId": "%X{context.caseId:-}",
64
            "class": "%logger{40}",
65
            "rest": "%message"
66
            }
67
          </pattern>
68
        </pattern>
69
      </providers>
70
    </encoder>
71
  </appender>
72
  
73
  <root level="INFO">
74
    <appender-ref ref="console"/>
75
    <!-- uncomment this to have also JSON logs -->
76
    <appender-ref ref="logstash"/>
77
    <appender-ref ref="flatfile"/>
78
  </root>
79
</configuration>
80
 
          



src/main/java/com.dzone.sample.logging

Java
 




xxxxxxxxxx
1
39


 
1
package com.dzone.sample.logging;
2
 
          
3
import java.io.IOException;
4
import javax.servlet.FilterChain;
5
import javax.servlet.ServletException;
6
import javax.servlet.ServletRequest;
7
import javax.servlet.ServletResponse;
8
import javax.servlet.http.HttpServletRequest;
9
import org.slf4j.Logger;
10
import org.slf4j.LoggerFactory;
11
import org.slf4j.MDC;
12
import org.springframework.stereotype.Component;
13
import org.springframework.web.filter.GenericFilterBean;
14
 
          
15
@Component
16
public class CoreAppThreeMDCFilter extends GenericFilterBean {
17
 
          
18
  private static final Logger logger = LoggerFactory.getLogger(CoreAppThreeMDCFilter.class);
19
 
          
20
  @Override
21
  public void destroy() {
22
  }
23
 
          
24
  @Override
25
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
26
      FilterChain filterChain) throws IOException, ServletException {
27
 
          
28
    MDC.put("context.userId", ((HttpServletRequest) servletRequest).getHeader("context.userId"));
29
    MDC.put("context.moduleId", "CoreAppThreeService");
30
    MDC.put("context.caseId", ((HttpServletRequest) servletRequest).getHeader("context.caseId"));
31
 
          
32
    logger.trace("A TRACE Message");
33
    logger.debug("A DEBUG Message");
34
    logger.info("An INFO Message");
35
    logger.warn("A WARN Message");
36
    logger.error("An ERROR Message");
37
    filterChain.doFilter(servletRequest, servletResponse);
38
  }
39
}



src/main/java/com.dzone.sample.logging

Java
 




xxxxxxxxxx
1
36


 
1
package com.dzonea.sample.logging;
2
 
          
3
import org.slf4j.Logger;
4
import org.slf4j.LoggerFactory;
5
import org.springframework.boot.SpringApplication;
6
import org.springframework.boot.autoconfigure.SpringBootApplication;
7
import org.springframework.context.annotation.Bean;
8
import org.springframework.web.bind.annotation.RequestMapping;
9
import org.springframework.web.bind.annotation.RestController;
10
import org.springframework.web.client.RestTemplate;
11
 
          
12
@RestController
13
@SpringBootApplication
14
public class LoggingCoreApplicationThree {
15
 
          
16
  private static final Logger logger = LoggerFactory.getLogger(LoggingCoreApplicationThree.class);
17
 
          
18
  public static void main(String[] args) {
19
    SpringApplication.run(LoggingCoreApplicationThree.class, args);
20
  }
21
 
          
22
  @Bean
23
  public RestTemplate getRestTemplate() {
24
    return new RestTemplate();
25
  }
26
 
          
27
  @RequestMapping("/coreapp3")
28
  public String rageService() throws Exception {
29
    logger.trace("A TRACE Message");
30
    logger.debug("A DEBUG Message");
31
    logger.info("An INFO Message");
32
    logger.warn("A WARN Message");
33
    logger.error("An ERROR Message");
34
    return "This is CoreAppThree Service ";
35
  }
36
}



Configure LogStash PipeLine

/usr/local/logstash-7.5.1/config/logstash.conf

Java
 




xxxxxxxxxx
1
28


 
1
input {
2
  file {
3
    path =>  [ "/Users/703258481mac/Marutha/Genpact/PVAI/IntelliJWorkspace/build/*.json" ]
4
    codec =>   json {
5
      charset => "UTF-8"
6
    }
7
  }
8
}
9
 
          
10
filter {
11
  if [message] =~ "timestamp" {
12
    grok {
13
      match => ["message", "^(timestamp)"]
14
      add_tag => ["stacktrace"]
15
    }
16
  }
17
} 
18
 
          
19
output {
20
  stdout {
21
    codec => rubydebug
22
  }
23
 
24
  elasticsearch {
25
    hosts => ["localhost:9200"]
26
  }
27
}
28
 
          



Start LogStash:

/usr/local/logstash-7.5.1/bin

./logstash -f ../config/logstash.conf

Sample Logstash Pipeline execution log

code screenshot


Start Kibana

/usr/local/var/homebrew/linked/kibana-full/bin

./kibana


Start ElasticSearch

/usr/local/var/homebrew/linked/elasticsearch-full/bin

./elasticsearch


Once all the Servers are started, then hit the CoreAppOne Service in Browser.

http://localhost:8080/coreapp1

This CoreAppOne Service calls CoreAppServiceTwo, which intern calls CoreAppServiceThree.

Now, you can able to see both Console logs and JSON logs under Your Workspace/build folder

Let's Connect to Kibana to configure the Logstash index

http://localhost:5601

kibana


kibana


index patterns


create index pattern step one


create index pattern step two


kibana discovery


CoreAppLogStash


CoreAppLogTrace

Java (programming language) Traceability application

Opinions expressed by DZone contributors are their own.

Related

  • A Systematic Approach for Java Software Upgrades
  • Building a Simple RAG Application With Java and Quarkus
  • Dust Actors and Large Language Models: An Application
  • Five Java Developer Must-Haves for Ultra-Fast Startup Solutions

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!