SlideShare a Scribd company logo
1 of 31
Download to read offline
I Can See Clearly Now
Observing and understanding
your Spring Applications at runtime
Observability
“To acquire knowledge, one must study;
but to acquire wisdom, one must observe.”
― Marilyn vos Savant
Observability
 Term in use since ca. 2013, increasingly popular
 Fancy term for monitoring?
Observability
 More focus on gaining insight into actual workings
 Not just known failure modes
 And without the need to deploy
new software
 Debugging the
“unknown unknowns”
The Three Pillars Of Observability
Logging
“it's log, log!
it's better than bad, it's good!
Everyone wants a log!
You're gonna love it, log!
Come on and get your log!
Everyone needs a log!”
― The Log Song, Ren & Stimpy
Logging In Spring Boot
 Logback by default, support for Log4J 2 etc.
 Some features:
 Colored Console logging
 Reusable log config fragments
 Reference Spring properties in logback-spring.xml
 Configure aspects using Spring properties,
e.g. log levels
Log Aggregation
 Days of grepping and tailing log files are over
 Too many services, not enough history, unknown
servers, correlate several logs, etc,
 Ship logs to log aggregation server
 Custom appender
 Beware of latency and buffering issues!
 Log shipper outside app
Patterns vs Structured Logging
 Logging output often follows pattern
 Problematic
 Lossy, hard to parse, multiline messages
Patterns vs Structured Logging
 Structured logs don’t have these problems
 Typically use JSON
 Supported by many aggregators as-is
 Easy to add additional fields
{"@timestamp":"2020-11-16T09:34:25.118+01:00",
"message":"Starting service [Tomcat]",
"logger.name":"org.apache.catalina.core.StandardService",
"logger.thread_name":"main","level":"INFO",
"service":"player-experience","region":"eu-west-1"}
logback-spring.xml
<configuration>
<property name="environment" value="${ENVIRONMENT:-local}"/>
<include resource="org/sfw/boot/logging/logback/defaults.xml" />
<include resource="org/sfw/boot/logging/logback/console-appender.xml" />
<include resource="console-json-appender.xml" />
…
<root level="INFO">
<if condition='property("environment").equals("local")'>
<then><appender-ref ref="CONSOLE"/></then>
<else><appender-ref ref="CONSOLE_JSON"/></else>
</if>
</root>
</configuration>
console-json-appender.xml
<included>
<springProperty name="service" source="spring.application.name/>
<define name="awsRegion"
class="nlo.gateway.logging.AwsRegionPropertyDefiner"/>
<appender name="CONSOLE_JSON"
class="ch.qos.logback.core.ConsoleAppender">
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<customFields>{"service":"${service}",
"region":"${awsRegion}"}</customFields>
</encoder>
</appender>
…
</included>
Logback PropertyProvider
import ch.qos.logback.core.PropertyDefinerBase;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
public class AwsRegionPropertyDefiner extends PropertyDefinerBase {
@Override
public String getPropertyValue() {
Region currentRegion = Regions.getCurrentRegion();
return currentRegion != null ? currentRegion.getName() : "-";
}
}
What To Log?
 Events that show what your code is doing
 More that just errors
 With sufficient contextual information!
 Parameters
 Currently executing request URL, batch job, …
 Logged in user
 Consider what goes in message vs. Mapped
Diagnostic Context (MDC)
MDC
 Key-value pairs associated with current thread
 Made available for logging
 Standard feature in most logging frameworks
 Many use cases
 Current user, tenant, request URL, etc.
public class MdcPopulatingFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
FilterChain chain) throws ServletException, IOException {
String requestURI = req.getRequestURI();
try (var u = MDC.putCloseable("uri", requestURI)) {
chain.doFilter(request, response);
}
}
Log Levels
 Pro-tip: use Spring config for easy per-
environment log levels
 Nice to combine with centralized configuration
 Also: Spring Boot Actuator allows on-the-fly
log level adjustments
 Nice to combine with Spring Boot Admin
logging.level.nl.trifork.client.ws.MessageTracing=debug
application-local.properties
Metrics
“What’s measured improves”
― Peter Drucker
Metrics
 Pre-aggregated numeric info
 Counters, timers, gauge, distribution-summary, …
 Like mix, max, avg response times for MVC controllers
 Very different from individual log events
 Enriched with tags or dimensions
 Like HTTP method, path, status code, …
 Sent to time-series DB for storing
 For dashboarding and alerting
 Slicing & dicing based on tags
Metrics
 Boot 2.x ships with Micrometer integration
 Metrics façade: SLF4J for metrics
 Instruments many Spring components
 Easy to add your own metrics
 Many backends supported
 Adapts automatically
 Push / pull
 Dimensional / hierarchic
 Naming conventions / limitations
Metrics Benefits
Compared to logging:
 Scales much better: bigger numbers, not more
 Faster to work with for big periods of time
 Cheaper to store
 Provides lots of insight into both infra and busines
without doing any work
Common Tags
@Bean
MeterRegistryCustomizer<MeterRegistry> commonTags(Environment env) {
Region awsRegion = Regions.getCurrentRegion();
return registry -> registry.config().commonTags(
"service", env.getProperty("spring.application.name),
"region", awsRegion != null ? awsRegion.getName() : "-"
);
}
 Tags sent with every metric
Tagging Monitoring Requests
@Bean
MeterFilter monitoringRequestTaggingMeterFilter() {
return new MeterFilter() {
@Override
public Meter.Id map(Meter.Id id) {
boolean monitoringRequest = false;
ServletRequestAttributes reqAttrs = (ServletRequestAttributes)
RequestContextHolder.getRequestAttributes();
if (reqAttrs != null) {
monitoringRequest = "true".equalsIgnoreCase(
reqAttrs.getRequest().getHeader(“X-Monitoring"));
}
return id.withTag(
Tag.of("monitoring_request", Boolean.toString(monitoringRequest)));
}
};
}
* does require RequestContextListener bean registered
Tracing
“A lost road will remember your footsteps because
someday you may want to return, tracing the way.”
― Munia Khan
Traces and Slices
 Trace ID generated once per incoming request,
propagated with downstream calls
 Every hop start a new slice within the trace
 Actual network hop, or logical within a service
 Can be exported to tracing DB
 Zipkin, Jaeger, custom APM solutions, …
 Often based on sampling
Distributed Tracing
 Spring Cloud Sleuth allows distributed tracing
 Propagating correlation ID per logical request
 Uses OpenZipkin’s Brave
 Instruments many Spring components
Brave vs. AMZN Trace IDs
 AWS LBs can add X-AMZN-Trace-ID header
 Format incompatible with Brave’s Trace ID
 Self=1-67891234-12456789abcdef012345678;Root=1-
67891233-abcdef012345678912345678
 However, easy to forward through Sleuth:
spring.sleuth.baggage.remote-fields=
X-Amzn-Trace-Id,X-Monitoring
SLF4J MDC Integration
SLF4J MDC Integration
Expose Trace IDs in Responses
 Allows clients to reference trace ID when reporting errors
 No more browsing through logs “around 12:05”
public class TraceIdResponseHeaderFilter implements Filter {
@Autowired Tracer tracer;
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
Span currentSpan = this.tracer.currentSpan();
if (currentSpan != null) {
((HttpServletResponse) res).addHeader(
"X-TraceId", currentSpan.context().traceIdString());
}
chain.doFilter(req, res);
}
…
We Want More!
 Can only explain so much in 45 minutes
 Check out Boot Loot presentation from Spring IO ‘19
We Want More!
 Check out code snippets on GitHub
https://gist.github.com/jkuipers
 Esp. LoggingClientHttpRequestInterceptor
 Logging outgoing HTTP requests & responses
 Including auto-configuration via RestTemplateBuilder

More Related Content

What's hot

Zero to Sixty: AWS CloudFormation (DMG201) | AWS re:Invent 2013
Zero to Sixty: AWS CloudFormation (DMG201) | AWS re:Invent 2013Zero to Sixty: AWS CloudFormation (DMG201) | AWS re:Invent 2013
Zero to Sixty: AWS CloudFormation (DMG201) | AWS re:Invent 2013Amazon Web Services
 
Encode x NEAR: Technical Overview of NEAR 1
Encode x NEAR: Technical Overview of NEAR 1Encode x NEAR: Technical Overview of NEAR 1
Encode x NEAR: Technical Overview of NEAR 1KlaraOrban
 
(SEC404) Incident Response in the Cloud | AWS re:Invent 2014
(SEC404) Incident Response in the Cloud | AWS re:Invent 2014(SEC404) Incident Response in the Cloud | AWS re:Invent 2014
(SEC404) Incident Response in the Cloud | AWS re:Invent 2014Amazon Web Services
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Masoud Kalali
 
Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Maarten Balliauw
 
Of CORS thats a thing how CORS in the cloud still kills security
Of CORS thats a thing how CORS in the cloud still kills securityOf CORS thats a thing how CORS in the cloud still kills security
Of CORS thats a thing how CORS in the cloud still kills securityJohn Varghese
 
(SEC403) Building AWS Partner Applications Using IAM Roles | AWS re:Invent 2014
(SEC403) Building AWS Partner Applications Using IAM Roles | AWS re:Invent 2014(SEC403) Building AWS Partner Applications Using IAM Roles | AWS re:Invent 2014
(SEC403) Building AWS Partner Applications Using IAM Roles | AWS re:Invent 2014Amazon Web Services
 
(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or Less
(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or Less(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or Less
(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or LessAmazon Web Services
 
Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)
Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)
Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)Maarten Balliauw
 
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 201910 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019Matt Raible
 
(SEC315) NEW LAUNCH: Get Deep Visibility into Resource Configurations | AWS r...
(SEC315) NEW LAUNCH: Get Deep Visibility into Resource Configurations | AWS r...(SEC315) NEW LAUNCH: Get Deep Visibility into Resource Configurations | AWS r...
(SEC315) NEW LAUNCH: Get Deep Visibility into Resource Configurations | AWS r...Amazon Web Services
 
Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...
Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...
Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...Andrea Dottor
 
Red Team vs. Blue Team on AWS ~ re:Invent 2018
Red Team vs. Blue Team on AWS ~ re:Invent 2018Red Team vs. Blue Team on AWS ~ re:Invent 2018
Red Team vs. Blue Team on AWS ~ re:Invent 2018Teri Radichel
 
Cloud Security At Netflix, October 2013
Cloud Security At Netflix, October 2013Cloud Security At Netflix, October 2013
Cloud Security At Netflix, October 2013Jay Zarfoss
 
Microservices with Netflix OSS and Spring Cloud
Microservices with Netflix OSS and Spring CloudMicroservices with Netflix OSS and Spring Cloud
Microservices with Netflix OSS and Spring Cloudacogoluegnes
 
AWS Re:Invent - Securing HIPAA Compliant Apps in AWS
AWS Re:Invent - Securing HIPAA Compliant Apps in AWSAWS Re:Invent - Securing HIPAA Compliant Apps in AWS
AWS Re:Invent - Securing HIPAA Compliant Apps in AWSControl Group
 
February 2016 Webinar Series - Best Practices for IoT Security in the Cloud
February 2016 Webinar Series - Best Practices for IoT Security in the CloudFebruary 2016 Webinar Series - Best Practices for IoT Security in the Cloud
February 2016 Webinar Series - Best Practices for IoT Security in the CloudAmazon Web Services
 
(SEC406) NEW LAUNCH: Building Secure Applications with AWS Key Management Ser...
(SEC406) NEW LAUNCH: Building Secure Applications with AWS Key Management Ser...(SEC406) NEW LAUNCH: Building Secure Applications with AWS Key Management Ser...
(SEC406) NEW LAUNCH: Building Secure Applications with AWS Key Management Ser...Amazon Web Services
 

What's hot (20)

Zero to Sixty: AWS CloudFormation (DMG201) | AWS re:Invent 2013
Zero to Sixty: AWS CloudFormation (DMG201) | AWS re:Invent 2013Zero to Sixty: AWS CloudFormation (DMG201) | AWS re:Invent 2013
Zero to Sixty: AWS CloudFormation (DMG201) | AWS re:Invent 2013
 
Encode x NEAR: Technical Overview of NEAR 1
Encode x NEAR: Technical Overview of NEAR 1Encode x NEAR: Technical Overview of NEAR 1
Encode x NEAR: Technical Overview of NEAR 1
 
(SEC404) Incident Response in the Cloud | AWS re:Invent 2014
(SEC404) Incident Response in the Cloud | AWS re:Invent 2014(SEC404) Incident Response in the Cloud | AWS re:Invent 2014
(SEC404) Incident Response in the Cloud | AWS re:Invent 2014
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
 
Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...
 
OAuth 2.0 Threat Landscape
OAuth 2.0 Threat LandscapeOAuth 2.0 Threat Landscape
OAuth 2.0 Threat Landscape
 
Of CORS thats a thing how CORS in the cloud still kills security
Of CORS thats a thing how CORS in the cloud still kills securityOf CORS thats a thing how CORS in the cloud still kills security
Of CORS thats a thing how CORS in the cloud still kills security
 
(SEC403) Building AWS Partner Applications Using IAM Roles | AWS re:Invent 2014
(SEC403) Building AWS Partner Applications Using IAM Roles | AWS re:Invent 2014(SEC403) Building AWS Partner Applications Using IAM Roles | AWS re:Invent 2014
(SEC403) Building AWS Partner Applications Using IAM Roles | AWS re:Invent 2014
 
(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or Less
(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or Less(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or Less
(SEC305) How to Become an IAM Policy Ninja in 60 Minutes or Less
 
Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)
Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)
Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)
 
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 201910 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
 
Javacro 2014 Spring Security 3 Speech
Javacro 2014 Spring Security 3 SpeechJavacro 2014 Spring Security 3 Speech
Javacro 2014 Spring Security 3 Speech
 
(SEC315) NEW LAUNCH: Get Deep Visibility into Resource Configurations | AWS r...
(SEC315) NEW LAUNCH: Get Deep Visibility into Resource Configurations | AWS r...(SEC315) NEW LAUNCH: Get Deep Visibility into Resource Configurations | AWS r...
(SEC315) NEW LAUNCH: Get Deep Visibility into Resource Configurations | AWS r...
 
Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...
Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...
Come sta la nostra applicazione? Un viaggio alla scoperta degli Health Check ...
 
Red Team vs. Blue Team on AWS ~ re:Invent 2018
Red Team vs. Blue Team on AWS ~ re:Invent 2018Red Team vs. Blue Team on AWS ~ re:Invent 2018
Red Team vs. Blue Team on AWS ~ re:Invent 2018
 
Cloud Security At Netflix, October 2013
Cloud Security At Netflix, October 2013Cloud Security At Netflix, October 2013
Cloud Security At Netflix, October 2013
 
Microservices with Netflix OSS and Spring Cloud
Microservices with Netflix OSS and Spring CloudMicroservices with Netflix OSS and Spring Cloud
Microservices with Netflix OSS and Spring Cloud
 
AWS Re:Invent - Securing HIPAA Compliant Apps in AWS
AWS Re:Invent - Securing HIPAA Compliant Apps in AWSAWS Re:Invent - Securing HIPAA Compliant Apps in AWS
AWS Re:Invent - Securing HIPAA Compliant Apps in AWS
 
February 2016 Webinar Series - Best Practices for IoT Security in the Cloud
February 2016 Webinar Series - Best Practices for IoT Security in the CloudFebruary 2016 Webinar Series - Best Practices for IoT Security in the Cloud
February 2016 Webinar Series - Best Practices for IoT Security in the Cloud
 
(SEC406) NEW LAUNCH: Building Secure Applications with AWS Key Management Ser...
(SEC406) NEW LAUNCH: Building Secure Applications with AWS Key Management Ser...(SEC406) NEW LAUNCH: Building Secure Applications with AWS Key Management Ser...
(SEC406) NEW LAUNCH: Building Secure Applications with AWS Key Management Ser...
 

Similar to Observing Spring Apps Runtime

Logging, tracing and metrics: Instrumentation in .NET 5 and Azure
Logging, tracing and metrics: Instrumentation in .NET 5 and AzureLogging, tracing and metrics: Instrumentation in .NET 5 and Azure
Logging, tracing and metrics: Instrumentation in .NET 5 and AzureAlex Thissen
 
Observability foundations in dynamically evolving architectures
Observability foundations in dynamically evolving architecturesObservability foundations in dynamically evolving architectures
Observability foundations in dynamically evolving architecturesBoyan Dimitrov
 
2 years with python and serverless
2 years with python and serverless2 years with python and serverless
2 years with python and serverlessHector Canto
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdfhamzadamani7
 
Sherlock Homepage - A detective story about running large web services - NDC ...
Sherlock Homepage - A detective story about running large web services - NDC ...Sherlock Homepage - A detective story about running large web services - NDC ...
Sherlock Homepage - A detective story about running large web services - NDC ...Maarten Balliauw
 
Logisland "Event Mining at scale"
Logisland "Event Mining at scale"Logisland "Event Mining at scale"
Logisland "Event Mining at scale"Thomas Bailet
 
Elastic Morocco Meetup Nov 2020
Elastic Morocco Meetup Nov 2020Elastic Morocco Meetup Nov 2020
Elastic Morocco Meetup Nov 2020Anna Ossowski
 
Sherlock Homepage (Maarten Balliauw)
Sherlock Homepage (Maarten Balliauw)Sherlock Homepage (Maarten Balliauw)
Sherlock Homepage (Maarten Balliauw)Visug
 
Sherlock Homepage - A detective story about running large web services (VISUG...
Sherlock Homepage - A detective story about running large web services (VISUG...Sherlock Homepage - A detective story about running large web services (VISUG...
Sherlock Homepage - A detective story about running large web services (VISUG...Maarten Balliauw
 
Intelligent Monitoring
Intelligent MonitoringIntelligent Monitoring
Intelligent MonitoringIntelie
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play FrameworkKnoldus Inc.
 
Native container monitoring
Native container monitoringNative container monitoring
Native container monitoringRohit Jnagal
 
Monitoring Error Logs at Databricks
Monitoring Error Logs at DatabricksMonitoring Error Logs at Databricks
Monitoring Error Logs at DatabricksAnyscale
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session ManagementFahad Golra
 
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, EverAltitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, EverFastly
 
Tuning Elasticsearch Indexing Pipeline for Logs
Tuning Elasticsearch Indexing Pipeline for LogsTuning Elasticsearch Indexing Pipeline for Logs
Tuning Elasticsearch Indexing Pipeline for LogsSematext Group, Inc.
 
Taking care of a cloud environment
Taking care of a cloud environmentTaking care of a cloud environment
Taking care of a cloud environmentMaarten Balliauw
 
A practical introduction to observability
A practical introduction to observabilityA practical introduction to observability
A practical introduction to observabilityNikolay Stoitsev
 

Similar to Observing Spring Apps Runtime (20)

Logging, tracing and metrics: Instrumentation in .NET 5 and Azure
Logging, tracing and metrics: Instrumentation in .NET 5 and AzureLogging, tracing and metrics: Instrumentation in .NET 5 and Azure
Logging, tracing and metrics: Instrumentation in .NET 5 and Azure
 
Observability foundations in dynamically evolving architectures
Observability foundations in dynamically evolving architecturesObservability foundations in dynamically evolving architectures
Observability foundations in dynamically evolving architectures
 
2 years with python and serverless
2 years with python and serverless2 years with python and serverless
2 years with python and serverless
 
Log4j2
Log4j2Log4j2
Log4j2
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
 
Sherlock Homepage - A detective story about running large web services - NDC ...
Sherlock Homepage - A detective story about running large web services - NDC ...Sherlock Homepage - A detective story about running large web services - NDC ...
Sherlock Homepage - A detective story about running large web services - NDC ...
 
Logisland "Event Mining at scale"
Logisland "Event Mining at scale"Logisland "Event Mining at scale"
Logisland "Event Mining at scale"
 
Elastic Morocco Meetup Nov 2020
Elastic Morocco Meetup Nov 2020Elastic Morocco Meetup Nov 2020
Elastic Morocco Meetup Nov 2020
 
Sherlock Homepage (Maarten Balliauw)
Sherlock Homepage (Maarten Balliauw)Sherlock Homepage (Maarten Balliauw)
Sherlock Homepage (Maarten Balliauw)
 
Sherlock Homepage - A detective story about running large web services (VISUG...
Sherlock Homepage - A detective story about running large web services (VISUG...Sherlock Homepage - A detective story about running large web services (VISUG...
Sherlock Homepage - A detective story about running large web services (VISUG...
 
Intelligent Monitoring
Intelligent MonitoringIntelligent Monitoring
Intelligent Monitoring
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
 
Native container monitoring
Native container monitoringNative container monitoring
Native container monitoring
 
Native Container Monitoring
Native Container MonitoringNative Container Monitoring
Native Container Monitoring
 
Monitoring Error Logs at Databricks
Monitoring Error Logs at DatabricksMonitoring Error Logs at Databricks
Monitoring Error Logs at Databricks
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, EverAltitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
Altitude NY 2018: Leveraging Log Streaming to Build the Best Dashboards, Ever
 
Tuning Elasticsearch Indexing Pipeline for Logs
Tuning Elasticsearch Indexing Pipeline for LogsTuning Elasticsearch Indexing Pipeline for Logs
Tuning Elasticsearch Indexing Pipeline for Logs
 
Taking care of a cloud environment
Taking care of a cloud environmentTaking care of a cloud environment
Taking care of a cloud environment
 
A practical introduction to observability
A practical introduction to observabilityA practical introduction to observability
A practical introduction to observability
 

Recently uploaded

Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 

Recently uploaded (20)

Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 

Observing Spring Apps Runtime

  • 1. I Can See Clearly Now Observing and understanding your Spring Applications at runtime
  • 2. Observability “To acquire knowledge, one must study; but to acquire wisdom, one must observe.” ― Marilyn vos Savant
  • 3. Observability  Term in use since ca. 2013, increasingly popular  Fancy term for monitoring?
  • 4. Observability  More focus on gaining insight into actual workings  Not just known failure modes  And without the need to deploy new software  Debugging the “unknown unknowns”
  • 5. The Three Pillars Of Observability
  • 6. Logging “it's log, log! it's better than bad, it's good! Everyone wants a log! You're gonna love it, log! Come on and get your log! Everyone needs a log!” ― The Log Song, Ren & Stimpy
  • 7. Logging In Spring Boot  Logback by default, support for Log4J 2 etc.  Some features:  Colored Console logging  Reusable log config fragments  Reference Spring properties in logback-spring.xml  Configure aspects using Spring properties, e.g. log levels
  • 8. Log Aggregation  Days of grepping and tailing log files are over  Too many services, not enough history, unknown servers, correlate several logs, etc,  Ship logs to log aggregation server  Custom appender  Beware of latency and buffering issues!  Log shipper outside app
  • 9. Patterns vs Structured Logging  Logging output often follows pattern  Problematic  Lossy, hard to parse, multiline messages
  • 10. Patterns vs Structured Logging  Structured logs don’t have these problems  Typically use JSON  Supported by many aggregators as-is  Easy to add additional fields {"@timestamp":"2020-11-16T09:34:25.118+01:00", "message":"Starting service [Tomcat]", "logger.name":"org.apache.catalina.core.StandardService", "logger.thread_name":"main","level":"INFO", "service":"player-experience","region":"eu-west-1"}
  • 11. logback-spring.xml <configuration> <property name="environment" value="${ENVIRONMENT:-local}"/> <include resource="org/sfw/boot/logging/logback/defaults.xml" /> <include resource="org/sfw/boot/logging/logback/console-appender.xml" /> <include resource="console-json-appender.xml" /> … <root level="INFO"> <if condition='property("environment").equals("local")'> <then><appender-ref ref="CONSOLE"/></then> <else><appender-ref ref="CONSOLE_JSON"/></else> </if> </root> </configuration>
  • 12. console-json-appender.xml <included> <springProperty name="service" source="spring.application.name/> <define name="awsRegion" class="nlo.gateway.logging.AwsRegionPropertyDefiner"/> <appender name="CONSOLE_JSON" class="ch.qos.logback.core.ConsoleAppender"> <encoder class="net.logstash.logback.encoder.LogstashEncoder"> <customFields>{"service":"${service}", "region":"${awsRegion}"}</customFields> </encoder> </appender> … </included>
  • 13. Logback PropertyProvider import ch.qos.logback.core.PropertyDefinerBase; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; public class AwsRegionPropertyDefiner extends PropertyDefinerBase { @Override public String getPropertyValue() { Region currentRegion = Regions.getCurrentRegion(); return currentRegion != null ? currentRegion.getName() : "-"; } }
  • 14. What To Log?  Events that show what your code is doing  More that just errors  With sufficient contextual information!  Parameters  Currently executing request URL, batch job, …  Logged in user  Consider what goes in message vs. Mapped Diagnostic Context (MDC)
  • 15. MDC  Key-value pairs associated with current thread  Made available for logging  Standard feature in most logging frameworks  Many use cases  Current user, tenant, request URL, etc. public class MdcPopulatingFilter extends OncePerRequestFilter { protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException { String requestURI = req.getRequestURI(); try (var u = MDC.putCloseable("uri", requestURI)) { chain.doFilter(request, response); } }
  • 16. Log Levels  Pro-tip: use Spring config for easy per- environment log levels  Nice to combine with centralized configuration  Also: Spring Boot Actuator allows on-the-fly log level adjustments  Nice to combine with Spring Boot Admin logging.level.nl.trifork.client.ws.MessageTracing=debug application-local.properties
  • 18. Metrics  Pre-aggregated numeric info  Counters, timers, gauge, distribution-summary, …  Like mix, max, avg response times for MVC controllers  Very different from individual log events  Enriched with tags or dimensions  Like HTTP method, path, status code, …  Sent to time-series DB for storing  For dashboarding and alerting  Slicing & dicing based on tags
  • 19. Metrics  Boot 2.x ships with Micrometer integration  Metrics façade: SLF4J for metrics  Instruments many Spring components  Easy to add your own metrics  Many backends supported  Adapts automatically  Push / pull  Dimensional / hierarchic  Naming conventions / limitations
  • 20. Metrics Benefits Compared to logging:  Scales much better: bigger numbers, not more  Faster to work with for big periods of time  Cheaper to store  Provides lots of insight into both infra and busines without doing any work
  • 21. Common Tags @Bean MeterRegistryCustomizer<MeterRegistry> commonTags(Environment env) { Region awsRegion = Regions.getCurrentRegion(); return registry -> registry.config().commonTags( "service", env.getProperty("spring.application.name), "region", awsRegion != null ? awsRegion.getName() : "-" ); }  Tags sent with every metric
  • 22. Tagging Monitoring Requests @Bean MeterFilter monitoringRequestTaggingMeterFilter() { return new MeterFilter() { @Override public Meter.Id map(Meter.Id id) { boolean monitoringRequest = false; ServletRequestAttributes reqAttrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (reqAttrs != null) { monitoringRequest = "true".equalsIgnoreCase( reqAttrs.getRequest().getHeader(“X-Monitoring")); } return id.withTag( Tag.of("monitoring_request", Boolean.toString(monitoringRequest))); } }; } * does require RequestContextListener bean registered
  • 23. Tracing “A lost road will remember your footsteps because someday you may want to return, tracing the way.” ― Munia Khan
  • 24. Traces and Slices  Trace ID generated once per incoming request, propagated with downstream calls  Every hop start a new slice within the trace  Actual network hop, or logical within a service  Can be exported to tracing DB  Zipkin, Jaeger, custom APM solutions, …  Often based on sampling
  • 25. Distributed Tracing  Spring Cloud Sleuth allows distributed tracing  Propagating correlation ID per logical request  Uses OpenZipkin’s Brave  Instruments many Spring components
  • 26. Brave vs. AMZN Trace IDs  AWS LBs can add X-AMZN-Trace-ID header  Format incompatible with Brave’s Trace ID  Self=1-67891234-12456789abcdef012345678;Root=1- 67891233-abcdef012345678912345678  However, easy to forward through Sleuth: spring.sleuth.baggage.remote-fields= X-Amzn-Trace-Id,X-Monitoring
  • 29. Expose Trace IDs in Responses  Allows clients to reference trace ID when reporting errors  No more browsing through logs “around 12:05” public class TraceIdResponseHeaderFilter implements Filter { @Autowired Tracer tracer; public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { Span currentSpan = this.tracer.currentSpan(); if (currentSpan != null) { ((HttpServletResponse) res).addHeader( "X-TraceId", currentSpan.context().traceIdString()); } chain.doFilter(req, res); } …
  • 30. We Want More!  Can only explain so much in 45 minutes  Check out Boot Loot presentation from Spring IO ‘19
  • 31. We Want More!  Check out code snippets on GitHub https://gist.github.com/jkuipers  Esp. LoggingClientHttpRequestInterceptor  Logging outgoing HTTP requests & responses  Including auto-configuration via RestTemplateBuilder