Skip to content
ImagineWorld

Monitoring, Tracing, and Distributed Logging

node_idnode-book_the-linux-devops-handbook_chapter-10-monitoring-tracing-and-distributed-logging
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleMonitoring, Tracing, and Distributed Logging
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 10 — Monitoring, Tracing, and Distributed Logging

Section titled “Chapter 10 — Monitoring, Tracing, and Distributed Logging”

Applications developed nowadays tend to be running inside Docker containers or as a serverless application stack. Traditionally, applications were built as a monolithic entity—one process running on a server. All logs were stored on a disk. It made it easy to get to the right information quickly. To diagnose a problem with your application, you had to log in to a server and search through logs or stack traces to get to the bottom of the problem. But when you run your application inside a Kubernetes cluster in multiple containers that are executed on different servers, things get complicated.

This also makes it very difficult to store logs, let alone view them. In fact, while running applications inside a container, it’s not advisable to save any files inside it. Oftentimes, we run those containers in a read-only filesystem. This is understandable as you should treat a running container as an ephemeral identity that can be killed at any time.

We face an identical situation when running serverless applications; on Amazon Web Services (AWS) Lambda, the process starts when you get a request, data inside that request gets processed, and the application dies after it finishes its job. If you happen to save anything to disk, it will get deleted once processing is concluded.

The most logical solution is, of course, sending all logs to some external system that will save, catalog, and make your logs searchable. There are multiple solutions, including Software as a Service (SaaS) and cloud-specific applications.

Incidentally, sending logs to an external system is also beneficial for bare-metal servers—for analysis and alerting, or diagnosing if you happen to lose access to the server or it stops responding.

Along with system and application logs, we can also send application-tracing metrics. Tracing is a more in-depth form of metrics where the application will provide you with more insights into system performance and how it behaves in given circumstances. Examples of trace data are the time in which a given request was handled by your application, how many CPU cycles it took, and how long your application was waiting for a database to respond.

In this chapter, you will learn about the following:

  • What are monitoring, tracing, and logging?
  • How to choose and configure one of the cloud-ready logging solutions
  • Self-hosted solutions and how to choose them
  • SaaS solutions and how to evaluate which will be most useful for your organization

Additionally, we will be covering the following topics:

  • Differences between monitoring, tracing, and logging
  • Cloud solutions
  • Open source solutions for self-hosting
  • SaaS solutions
  • Log and metrics retention

So, let’s jump right into it!

Differences between monitoring, tracing, and logging

Section titled “Differences between monitoring, tracing, and logging”

You will hear these terms being used interchangeably depending on the context and person you’re talking to, but there’s a subtle and very important difference between them.

Monitoring refers to instrumenting your servers and applications and gathering data about them for processing, identifying problems, and, in the end, bringing results in front of interested parties. This also includes alerting.

Tracing, on the other hand, is more specific, as we already mentioned. Trace data can tell you a lot about how your system is performing. With tracing, you can observe statistics that are very useful to developers (such as how long a function ran and whether the SQL query is fast or bottleneck), DevOps engineers (how long we were waiting for a database or network), or even the business (what was the experience of the user with our application?). So, you can see that when it’s used right, it can be a very powerful tool under your belt.

The purpose of logging is to bring actionable information in a centralized way, which commonly is just saving all messages to a file (it’s called a log file). These messages typically consist of the success or failure of a given operation with configurable verbosity. Logging is primarily used by system administrators or DevOps engineers to provide a better view of what’s going on in the operating system or with any given application.

With that cleared up, we can jump into specific implementations of the distributed monitoring solutions in the cloud, DIY solutions, or as a SaaS application.

Every cloud provider out there is fully aware of the need for proper monitoring and distributed logging, so they will have built their own native solutions. Sometimes it’s worth using native solutions, but not always. Let’s take a look at the major cloud providers and what they have to offer.

One of the first services available in AWS was CloudWatch. At first, it would just collect all kinds of metrics and allow you to create dashboards to better understand system performance and easily spot issues or simply a denial-of-service attack, which in turn allowed you to quickly react to them.

Another function of CloudWatch is alerting, but it’s limited to sending out emails using another Amazon service, Simple Email Service. Alerting and metrics could also trigger other actions inside your AWS account, such as scaling up or down the number of running instances.

As of the time of writing this book, CloudWatch can do so much more than monitoring. The developers of this service have added the ability to collect and search through logs (CloudWatch Logs Insights), monitor changes in AWS resources itself, and trigger actions. We’re also able to detect anomalies within our applications using CloudWatch anomaly detection.

As for tracing, AWS has prepared a service called AWS X-Ray, which is an advanced distributed tracing system that can give you information about how your application is working in the production environment in almost real time. Unfortunately, its capabilities are limited to only a couple of languages out there: Node.js, Java, and.NET. So, you’re out of luck if your application is written in Python.

Looking at other popular cloud solutions, there’s Google. The Google Cloud Platform (GCP) consists of a smart solution for gathering logs, querying, and error reporting, and it’s called… Cloud Logging. If using this service within GCP, similarly to CloudWatch Logs, you will be able to send your application logs, store them, search for data you need (IP addresses, query strings, debug data, and so on), and analyze your logs by using SQL-like queries.

The similarities end here, though, as Google went a couple of steps further with additional features such as the ability to create log dashboards with visualizations of errors reported by your application, or creating log-based metrics.

In GCP, monitoring is carried out by another service entirely–Google Cloud Monitoring. It’s focused on gathering data about your application, creating Service-Level Objectives (SLOs), extensive metrics collection from Kubernetes (Google Kubernetes Engine, or GKE), and third-party integrations, for example, with a well-known service such as Prometheus.

Looking at the Microsoft Cloud Platform—Azure—you will find Azure Monitor Service, which consists of several parts that cover the requirements for full-scope application monitoring and tracing. There is Azure Monitor Logs for gathering logs, obviously. There is also Azure Monitor Metrics for monitoring and visualizing all metrics you push there. You can also analyze, query, and set alerts like you would be able to in GCP or AWS. Tracing is being done by Azure Application Insights. It is being promoted by Microsoft as an Application Performance Management (APM) solution and is part of Azure Monitor. It offers a visual map of the application, real-time metrics, code analysis, usage data, and many more features. The implementation, obviously, differs between all cloud providers and their solutions. You will have to refer to the documentation on how to instrument and configure each of those services.

We will focus on AWS services. We will create a log group for our application and gather metrics from an EC2 instance. We will also talk about tracing with AWS X-Ray in Python, which we could use for our application running inside AWS infrastructure no matter the underlying service.

CloudWatch Logs is a log management service provided by AWS that enables you to centralize, search, and monitor log data from various sources in a single place. It allows you to troubleshoot operational problems and security incidents, as well as monitor resource utilization and performance.

CloudWatch metrics are a monitoring service provided by AWS that allows you to collect, track, and monitor various metrics for your AWS resources and applications.

CloudWatch metrics provide users with a detailed view of how their AWS resources are performing, by collecting and displaying key metrics, such as CPU utilization, network traffic, and disk I/O, and other metrics related to AWS resources, such as EC2 instances, RDS instances, S3 buckets, and Lambda functions.

Users can use CloudWatch metrics to set alarms that will notify them when certain thresholds are exceeded, as well as to create custom dashboards that display important metrics in near real time. CloudWatch metrics also allow users to retrieve and analyze historical data, which can be used to identify trends and optimize resource usage.

To be able to send logs and metrics to CloudWatch, we will need the following:

  • An IAM policy that grants permissions to send logs to CloudWatch Logs. Additionally, we will allow pushing metrics data along with the logs.
  • To create an IAM role with the previously created policy attached to it. This role then can be assumed by EC2 instances, Lambda functions, or any other AWS services that require the ability to send logs to CloudWatch Logs.
  • To attach the role to a resource that we want to send logs to CloudWatch Logs. For our purpose, we will attach the role to an EC2 instance.

An example of an IAM policy is as follows:

{
“Version”: “2012-10-17”,
“Statement”: [
{
“Sid”: “CloudWatchLogsPermissions”,
“Effect”: “Allow”,
“Action”: [
“logs:CreateLogStream”,
“logs:CreateLogGroup”,
“logs:PutLogEvents”
],
“Resource”: “arn:aws:logs:*:*:*”
},
{
“Sid”: “CloudWatchMetricsPermissions”,
“Effect”: “Allow”,
“Action”: [
“cloudwatch:PutMetricData”
],
“Resource”: “*”
}
]
}

In this policy, the logs:CreateLogStream and logs:PutLogEvents actions are allowed for all CloudWatch Logs resources (arn:aws:logs:*:*:*), and the cloudwatch:PutMetricData action is allowed for all CloudWatch metric resources (*).

We will also need a trust policy allowing EC2 to assume a role we’re going to create for it, in order to be able to send metrics and logs. The trust policy looks like this:

{
“Version”: “2012-10-17”,
“Statement”: [
{
“Effect”: “Allow”,
“Principal”: { “Service”: “ec2.amazonaws.com”},
“Action”: “sts:AssumeRole”
}
]
}

Save this to a trust-policy.json file, which we will use in a moment.

Using the AWS CLI tool, to create an instance profile and attach the preceding policy to it, you will need to run the following commands:

admin@myhome:~$ aws iam create-instance-profile --instance-profile-name DefaultInstanceProfile
{
“InstanceProfile”: {
“Path”: “/”,
“InstanceProfileName”: “DefaultInstanceProfile”,
“InstanceProfileId”: “AIPAZZUIKRXR3HEDBS72R”,
“Arn”: “arn:aws:iam::673522028003:instance-profile/DefaultInstanceProfile”,
“CreateDate”: “2023-03-07T10:59:01+00:00”,
“Roles”: []
}
}

We will also need a role with a trust policy attached to it:

admin@myhome:~$ aws iam create-role --role-name DefaultInstanceProfile --assume-role-policy-document file://trust-policy.json
{
“Role”: {
“Path”: “/”,
“RoleName”: “DefaultInstanceProfile”,
“RoleId”: “AROAZZUIKRXRYB6HO35BL”,
“Arn”: “arn:aws:iam::673522028003:role/DefaultInstanceProfile”,
“CreateDate”: “2023-03-07T11:13:54+00:00”,
“AssumeRolePolicyDocument”: {
“Version”: “2012-10-17”,
“Statement”: [
{
“Effect”: “Allow”,
“Principal”: {
“Service”: “ec2.amazonaws.com”
},
“Action”: “sts:AssumeRole”
}
]
}
}
}

Now, we can attach the role we just created to the instance profile, so we can use it in the EC2 instance:

admin@myhome:~$ aws iam add-role-to-instance-profile --role-name DefaultInstanceProfile --instance-profile-name DefaultInstanceProfile

And now, let’s attach a policy to use against the EC2 service:

admin@myhome:~$ aws iam put-role-policy --policy-name DefaultInstanceProfilePolicy --role-name DefaultInstanceProfile --policy-document file://policy.json

The policy.json file is the file where you’ve saved the policy.

An instance profile, as the name suggests, will work only with EC2 instances. To use the same policy for a Lambda function, we will need to create an IAM role instead and attach the newly created role to a function.

Let’s create a new instance using the AWS CLI as well, and attach the instance profile we’ve just created. This particular instance will be placed in a default VPC and in a public subnet. This will cause the instance to get a public IP address and will be available from the public internet.

To create an EC2 instance in a public subnet of the default VPC using DefaultInstanceProfile, you can follow these steps:

  1. Get the ID of the default VPC:
admin@myhome:~$ aws ec2 describe-vpcs --filters “Name=isDefault,Values=true” --query “Vpcs[0].VpcId” --output text
vpc-0030a3a495df38a0e

This command will return the ID of the default VPC. We will need it in the following steps.

  1. Get the ID of a public subnet in the default VPC and save it for later use:
admin@myhome:~$ aws ec2 describe-subnets --filters “Name=vpc-id,Values=vpc-0030a3a495df38a0e” “Name=map-public-ip-on-launch,Values=true” --query “Subnets[0].SubnetId” --output text subnet-0704b611fe8a6a169

To launch an EC2 instance, we will need an instance template called an Amazon Machine Image (AMI) and an SSH key that we will use to access this instance. To get an ID of an Ubuntu image, we can also use the AWS CLI tool.

  1. We will filter out the most recent AMI ID of Ubuntu 20.04 with the following command:
admin@myhome:~$ aws ec2 describe-images --owners 099720109477 --filters “Name=name,Values=*ubuntu/images/ hvm-ssd/ubuntu-focal-20.04*” “Name=state,Values=available” “Name=architecture,Values=x86_64” --query “reverse(sort_by(Images, &CreationDate))[:1].ImageId” --output text
ami-0a3823a4502bba678

This command will list all available Ubuntu 20.04 images owned by Canonical (099720109477) and filter them by name (ubuntu-focal-20.04-*), architecture (we need x86_64, not ARM), and whether they are available for use (state is available). It will also sort them by creation date in descending order and return the most recent (first on the list) image ID.

  1. Now, to create an SSH key, you will need to generate one for yourself or use the key you have already on your machine. We will need to upload a public part of our key to AWS. You can simply run another CLI command to achieve this:
admin@myhome:~$ aws ec2 import-key-pair --key-name admin-key --public-key-material fileb://home/admin/.ssh/admin-key.pub
{
“KeyFingerprint”: “12:97:23:0f:d6:2f:2b:28:4d:a0:ad:62:a7:20:e3:f8”,
“KeyName”: “admin-key”,
“KeyPairId”: “key-0831b2bc5c2a08d82”
}

With all that, finally, we’re ready to launch a new instance in the public subnet with DefaultInstanceProfile:

admin@myhome:~$ aws ec2 run-instances --image-id ami-0abbe417ed83c0b29 --count 1 --instance-type t2.micro --key-name admin-key --subnet-id subnet-0704b611fe8a6a169 --associate-public-ip-address --iam-instance-profile Name=DefaultInstanceProfile
{
“Groups”: [],
“Instances”: [
{
“AmiLaunchIndex”: 0,
“ImageId”: “ami-0abbe417ed83c0b29”,
“InstanceId”: “i-06f35cbb39f6e5cdb”,
“InstanceType”: “t2.micro”,
“KeyName”: “admin-key”,
“LaunchTime”: “2023-03-08T14:12:00+00:00”,
“Monitoring”: {
“State”: “disabled”
},
“Placement”: {
“AvailabilityZone”: “eu-central-1a”,
“GroupName”: “”,
“Tenancy”: “default”
},
“PrivateDnsName”: “ip-172-31-17-127.eu-central-1.compute.internal”,
“PrivateIpAddress”: “172.31.17.127”,
“ProductCodes”: [],
“PublicDnsName”: “”,
“State”: {
“Code”: 0,
“Name”: “pending”
},
“StateTransitionReason”: “”,
“SubnetId”: “subnet-0704b611fe8a6a169”,
“VpcId”: “vpc-0030a3a495df38a0e”,
“Architecture”: “x86_64”,
“BlockDeviceMappings”: [],
“ClientToken”: “5e4a0dd0-665b-4878-b852-0a6ff21c09d3”,
“EbsOptimized”: false,
“EnaSupport”: true,
“Hypervisor”: “xen”,
“IamInstanceProfile”: {
“Arn”: “arn:aws:iam::673522028003:instance-profile/DefaultInstanceProfile”,
“Id”: “AIPAZZUIKRXR3HEDBS72R”
},
# output cut for readability

The output of the preceding command is information about newly launched instances you could use for scripting purposes or simply to save the instance IP address for later use.

At this point, you won’t be able to connect to the machine yet as, by default, all ports are closed. To open the SSH port (22), we will need to create a new security group.

  1. Use the following command to achieve that:
admin@myhome:~$ aws ec2 create-security-group --group-name ssh-access-sg --description “Security group for SSH access” --vpc-id vpc-0030a3a495df38a0e
{
“GroupId”: “sg-076f8fad4e60192d8”
}

The VPC ID we used is the one we saved earlier in the process, and the output is the ID of our new security group. We will need to add an ingress rule to it and connect it to our EC2 instance. See the InstanceID value in the long output once the machine is created (i-06f35cbb39f6e5cdb).

  1. Use the following command to add an inbound rule to the security group that allows SSH access from 0.0.0.0/0:
admin@myhome:~$ aws ec2 authorize-security-group-ingress --group-id sg-076f8fad4e60192d8 --protocol tcp --port 22 --cidr 0.0.0.0/0
{
“Return”: true,
“SecurityGroupRules”: [
{
“SecurityGroupRuleId”: “sgr-0f3b4be7d2b01a7f6”,
“GroupId”: “sg-076f8fad4e60192d8”,
“GroupOwnerId”: “673522028003”,
“IsEgress”: false,
“IpProtocol”: “tcp”,
“FromPort”: 22,
“ToPort”: 22,
“CidrIpv4”: “0.0.0.0/0”
}
]
}

We’ve used the ID of the security group that we created in a previous step.

This command added a new inbound rule to the security group that allows TCP traffic on port 22 (SSH) from any IP address (0.0.0.0/0). Instead of allowing full internet access to your new EC2 instance, you could choose to use your own public IP address instead.

  1. Now, we can attach this security group to an instance:
admin@myhome:~$ aws ec2 modify-instance-attribute --instance-id i-06f35cbb39f6e5cdb --groups sg-076f8fad4e60192d8

At this point, port 22 should be open and ready to receive connections.

Let’s stop here for a moment. You’re probably wondering whether there is a better way to do this instead of with the AWS CLI. Yes, there is; there are various tools to automate the creation of the infrastructure. Those tools are generally called Infrastructure as Code (IaC) and we will talk about them in Chapter 12. There are various options we could have used in this example, from CloudFormation, which is the go-to IaC tool for AWS, to Terraform, from HashiCorp to the Pulumi project, which is gaining traction.

Now that we have an EC2 instance, we can connect to it and install the CloudWatch agent. It’s needed because AWS by default monitors only two metrics: CPU and memory usage. If you want to monitor disk space and send additional data to CloudWatch (such as logs or custom metrics), the agent is a must.

  1. After getting into the SSH console, we will need to download the CloudWatch agent deb package and install it using the dpkg tool:
admin@myhome:~$ ssh -i ~/.ssh/admin-key [email protected]
ubuntu@ip-172-31-17-127:~$ wget https://s3.amazonaws.com/amazoncloudwatch-agent/ubuntu/amd64/latest/amazon-cloudwatch-agent.deb
ubuntu@ip-172-31-17-127:~$ sudo dpkg -i -E ./amazon-cloudwatch-agent.deb

Let’s become the root user so we can omit sudo from every command:

ubuntu@ip-172-31-17-127:~$ sudo -i
root@ip-172-31-17-127:~# /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard
================================================================
= Welcome to the Amazon CloudWatch Agent Configuration Manager =
= =
= CloudWatch Agent allows you to collect metrics and logs from =
= your host and send them to CloudWatch. Additional CloudWatch =
= charges may apply. =
================================================================
On which OS are you planning to use the agent?
1. linux
2. windows
3. darwin
default choice: [1]:

It will ask a lot of questions, but it’s safe to leave most of them as their default and just hit Enter. There are some questions, however, that will require additional attention from us:

Do you want to monitor metrics from CollectD? WARNING: CollectD must be installed or the Agent will fail to start
1. yes
2. no
default choice: [1]:
  1. If you answered yes (1) to this question, you will need to install collectd by invoking the following command:
root@ip-172-31-17-127:~# apt install -y collectd
  1. To the following question, answer no (2) unless you want some particular log file to be uploaded to CloudWatch Logs:
Do you want to monitor any log files?
1. yes
2. no
default choice: [1]:
2
  1. The final question is whether to save the agent configuration in AWS SSM, to which you can safely answer no (2) as well:
Do you want to store the config in the SSM parameter store?
1. yes
2. no
default choice: [1]:
2
Program exits now.

The wizard will save the configuration in /opt/aws/amazon-cloudwatch-agent/bin/config.json. You will be able to alter it later or launch the wizard again if needed.

  1. Before we start the agent, we will need to convert the output JSON file into new Tom’s Obvious, Minimal Language (TOML) format, which is what the agent is using. Fortunately, there’s also a command for this job, too. We will use the agent control script to load the existing schema, save the TOML file, and optionally, start the agent if everything is in order:
root@ip-172-31-17-127:~# /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c file:/opt/aws/amazon-cloudwatch-agent/bin/config.json
root@ip-172-31-17-127:~# systemctl status amazon-cloudwatch-agent
amazon-cloudwatch-agent.service - Amazon CloudWatch Agent
Loaded: loaded (/etc/systemd/system/amazon-cloudwatch-agent.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2023-03-08 15:00:30 UTC; 4min 54s ago
Main PID: 20130 (amazon-cloudwat)
Tasks: 6 (limit: 1141)
Memory: 14.3M
CGroup: /system.slice/amazon-cloudwatch-agent.service
└─20130 /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent -config /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.toml -envconfig /opt/aws/amazon-cloudwatch-agent/e>
Mar 08 15:00:30 ip-172-31-17-127 systemd[1]: Started Amazon CloudWatch Agent.
Mar 08 15:00:30 ip-172-31-17-127 start-amazon-cloudwatch-agent[20130]: /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json does not exist or cannot read. Skipping it.
Mar 08 15:00:30 ip-172-31-17-127 start-amazon-cloudwatch-agent[20130]: I! Detecting run_as_user...

Now, we can go to the AWS web console and navigate to CloudWatch to see whether we can see the metrics coming in. It may take several minutes until they’re shown.

Before starting the CloudWatch agent, we will get about 17 different metrics for our EC2 instance, as seen in the following screenshot:

Figure 10.1 – Basic EC2 and EBS metrics in CloudWatch without the CloudWatch agent installed

After we’ve started the CloudWatch agent, we will start receiving a lot more metrics and we will see an additional namespace in the CloudWatch Metrics panel. See the following screenshot:

Figure 10.2 – CloudWatch metrics after successfully enabling the CloudWatch agent on the EC2 instance

All metrics we’re receiving can be used to create dashboards and alerts (including anomaly detection) in the CloudWatch service.

AWS X-Ray is a service that enables you to trace requests through distributed systems and microservice applications. It provides an end-to-end view of requests as they travel through an application, allowing developers to identify performance bottlenecks, diagnose errors, and improve overall application efficiency.

With X-Ray, it’s possible to visualize the different components of your application and see how requests are being processed as they travel through each component. This includes details such as the time taken to complete each component, any errors that occur, and the cause of those errors.

X-Ray also provides a range of analysis tools, including statistical analysis and heat maps, to help developers identify trends and patterns in request processing. These insights can be used to optimize performance and ensure that the application is running as efficiently as possible.

AWS X-Ray supports a wide range of programming languages, including the following:

  • Node.js
  • Java
  • .NET
  • Go
  • Python
  • Ruby
  • PHP

To instrument your application with the diagnostic tools provided by AWS X-Ray, you can use the AWS SDK. Consider the following code (found in the GitHub repository at https://github.com/Sysnove/flask-hello-world):

from flask import Flask
app = Flask(__name__)
@app.route(‘/’)
def hello_world():
return ‘Hello World!’
if __name__ == ‘__main__’:
app.run()

To gather tracing data about this service, you’ll need to install the aws_xray_sdk package using the pip package manager. Then, import the xray_recorder subpackage into our code. In this case, we will also use this SDK’s integration with the Flask framework. The modified code will look like this:

from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.ext.flask.middleware import XRayMiddleware
xray_recorder.configure(service=’FlaskHelloWorldApp’)
app = Flask(__name__)
XRayMiddleware(app, xray_recorder)

The rest of the code can remain unchanged. Here, we are configuring the X-Ray recorder to use the service name FlaskHelloWorldApp, which will show up in the X-Ray console as the name of our service. When the service starts running, you can go to the X-Ray console and see the service name FlaskHelloWorldApp with a list of traces.

The full documentation for the AWS X-Ray SDK can be found on this website: https://docs.aws.amazon.com/xray-sdk-for-python/latest/reference/index.html.

When running the preceding application on the EC2 instance we created in a previous section, you will see a complete picture of the running environment of your application including the internals of the running Flask processes.

There are multiple projects that deal with application monitoring, tracing, and gathering logs. Apart from cloud-hosted solutions that are available in the cloud environment, there are commercial and open source solutions worth knowing about. This awareness might prove useful when dealing with more and more common hybrid solutions.

One of the most popular projects built around monitoring that is also adopted by commercial solutions is OpenTelemetry. It’s an open source project for application monitoring and observability. It provides a set of APIs, libraries, agents, and integrations for collecting, processing, and exporting telemetry data such as traces, metrics, and logs from different sources in distributed systems. OpenTelemetry is designed to be vendor-agnostic and cloud-native, meaning it can work with various cloud providers, programming languages, frameworks, and architectures.

The main goal of OpenTelemetry is to provide developers and operators with a unified and standardized way to instrument, collect, and analyze telemetry data across the entire stack of their applications and services, regardless of the underlying infrastructure. OpenTelemetry supports different data formats, protocols, and export destinations, including popular observability platforms such as Prometheus, Jaeger, Zipkin, Grafana, and SigNoz. This allows users to mix and match their preferred tools and services to build a comprehensive observability pipeline that meets their specific needs.

Some examples of commercial software that adopts OpenTelemetry are Datadog, AWS, and New Relic. AWS provides OpenTelemetry Collector as a managed service for collecting and exporting telemetry data to AWS services such as Amazon CloudWatch, AWS X-Ray, and AWS App Runner.

Prometheus is an open source monitoring solution that is widely used for collecting and querying metrics from distributed systems. It was created by the developers at SoundCloud and is now maintained by the Cloud Native Computing Foundation (CNCF). Prometheus is designed to be highly scalable and adaptable, with support for a wide range of data sources and integration options. It allows users to define and collect custom metrics, visualize data through a built-in dashboard, and set alerts based on predefined thresholds or anomalies. Prometheus is often used in conjunction with Kubernetes and other cloud-native technologies, but it can also be used to monitor traditional infrastructure and applications.

One common use case is to track request latencies and error rates, which can help identify performance bottlenecks and potential issues in the application. To get started with monitoring a Flask application using Prometheus, you can use the Prometheus client library for Python. This library provides decorators that can be added to Flask routes to automatically generate metrics such as request count, request duration, and HTTP response codes. These metrics can then be collected by a Prometheus server and displayed on a Grafana dashboard for visualization and analysis.

Here’s an example of how you can instrument the “ Hello World ” Flask application with Prometheus to send metrics. We used the same application with AWS X-Ray in a previous section.

First, you’ll need to install the prometheus_client library using pip:

$ pip install prometheus_client

Next, you can modify the app.py file in the flask-hello-world repository to add the Prometheus client library and instrument the routes with metrics. Here’s an example:

from flask import Flask
from prometheus_client import Counter, Histogram, start_http_server
app = Flask(__name__)
# Define Prometheus metrics
REQUEST_COUNT = Counter(‘hello_world_request_count’, ‘Hello World Request Count’)
REQUEST_LATENCY = Histogram(‘hello_world_request_latency_seconds’, ‘Hello World Request Latency’,
bins=[0.1, 0.2, 0.5, 1.0, 5.0, 10.0, 30.0, 60.0])
# Instrument Flask routes with Prometheus metrics
@app.route(‘/’)
@REQUEST_LATENCY.time()
def hello():
REQUEST_COUNT.inc()
return “Hello World!”
# Start the Prometheus server on port 8000
if __name__ == ‘__main__’:
start_http_server(8000)
app.run(debug=True)

In this example, we’ve defined two Prometheus metrics: hello_world_request_count and hello_world_request_latency_seconds. The hello() route is instrumented with these metrics using decorators. The REQUEST_LATENCY histogram measures the request latency for each request, while the REQUEST_COUNT counter increments on each request.

We’ve started the Prometheus server on port 8000 using start_http_server(). This will make the metrics available for collection by a Prometheus server.

To view the metrics, you can navigate to http://localhost:8000/metrics in your web browser. This will display the raw metrics data in Prometheus format. You can also use a tool such as Grafana to visualize the metrics on a dashboard.

Grafana is a popular open source dashboard and data visualization platform that enables users to create interactive and customizable dashboards for monitoring and analyzing metrics from various data sources. It is usually used alongside Prometheus.

With Grafana, users can create visualizations, alerting rules, and dashboards that provide insight into the performance and behavior of their applications and infrastructure. Grafana supports a wide range of data sources, including popular time-series databases such as Prometheus, InfluxDB, and Graphite, making it a versatile tool for monitoring and visualization. Once you have connected your data source, you can start creating dashboards by adding panels to visualize the data. These panels can include various types of visualizations, including line graphs, bar charts, and gauges. You can also customize the dashboard layout, add annotations, and set up alerts to notify you of anomalies or issues in your metrics. With its powerful features and flexibility, Grafana is a go-to tool for visualizing and analyzing application and infrastructure metrics.

Grafana Labs also created the Grafana Loki project, which can be used to extend your monitoring with logs visualization. Grafana Loki is a horizontally scalable log aggregation system that provides a way to centralize logs from various sources and quickly search and analyze them. It’s being seen as an alternative to Prometheus, but both tools have different use cases and could be complementary to each other.

Loki, unlike traditional log management solutions, does not index or parse logs upfront. Instead, it uses a streaming pipeline that extracts log labels and stores them in a compact and efficient format, making it ideal for ingesting and querying large volumes of logs in real time. Grafana Loki integrates seamlessly with Grafana, allowing users to correlate logs with metrics and create powerful dashboards that provide insight into the behavior of their applications and infrastructure.

To use Grafana Loki, you need to set up a Loki server and configure it to receive log data from your applications and infrastructure. Once Loki is set up, you can use the Grafana Explore feature to search and visualize logs in real time. Explore provides a user-friendly interface that enables you to search logs using various filters, such as labels, time range, and query expressions

SigNoz is an observability platform that enables users to collect, store, and analyze application metrics’ telemetry data and provides log management under a single web panel. It is built on top of the OpenTelemetry specification, which is an industry-standard framework for distributed tracing and metric collection. SigNoz provides a simple, intuitive interface for users to view real-time and historical data about their applications’ performance and health.

SigNoz has its own agent that you can install on your servers, but it also supports Prometheus as a data source. So, if you’re already using Prometheus, you can use SigNoz without any significant changes to your monitoring infrastructure.

To install SigNoz on your server, you can follow a comprehensive guide on the official project website: https://signoz.io/docs/install/.

New Relic is a well-known monitoring SaaS solution; we will get back to it later in this chapter in the SaaS solutions section. Pixie is an open source project started by New Relic and was contributed to CNCF.

CNCF is an open source software foundation that was established in 2015 to advance the development and adoption of cloud-native technologies. CNCF is the home of many popular projects, such as Kubernetes, Prometheus, and Envoy, which are widely used in modern cloud-native applications. The foundation aims to create a vendor-neutral ecosystem for cloud-native computing, promoting interoperability and standardization among different cloud platforms and technologies. CNCF also hosts several certification programs that help developers and organizations validate their proficiency in cloud-native technologies. CNCF plays a critical role in driving innovation and standardization in the rapidly evolving cloud-native landscape.

New Relic Pixie is an open source, Kubernetes-native observability solution that provides real-time monitoring and tracing capabilities for modern applications. It can help developers and operations teams to quickly identify and troubleshoot performance issues in microservices-based applications running on Kubernetes clusters. Pixie can be easily deployed on any Kubernetes cluster and provides out-of-the-box support for popular open source tools such as Prometheus, Jaeger, and OpenTelemetry.

One of the key benefits of using New Relic Pixie is that it provides end-to-end visibility into the performance of applications and infrastructure, from the application code to the underlying Kubernetes resources. By collecting and analyzing data from various sources, including logs, metrics, and traces, Pixie can help pinpoint the root cause of performance bottlenecks and issues. This can significantly reduce the Mean Time to Resolution (MTTR) and improve application reliability and uptime.

Another advantage of New Relic Pixie is that it uses a unique instrumentation approach that does not require any code changes or configuration. Pixie uses extended Berkeley Packet Filter (eBPF) technology to collect performance data at the kernel level, allowing for low-overhead monitoring without adding any additional load to applications or infrastructure. This makes it an ideal solution for monitoring and tracing modern, cloud-native applications that are highly dynamic and scalable. Overall, New Relic Pixie provides a powerful and easy-to-use observability solution that can help teams to optimize the performance and reliability of their Kubernetes-based applications.

Graylog is an open source log management platform that allows users to collect, index, and analyze log data from various sources. The platform provides a centralized location for monitoring and troubleshooting applications, systems, and network infrastructure. It is built on top of Elasticsearch, MongoDB, and Apache Kafka, which ensures high scalability and availability.

Graylog has the ability to scale horizontally, which means that you can add additional Graylog nodes to handle increased log data volume and query load. The system can also distribute the workload across multiple nodes, which allows for efficient use of resources and faster processing of data. This scalability makes Graylog suitable for organizations of any size, from small start-ups to large enterprises.

Graylog uses Elasticsearch as the primary data store for indexing and searching log data. Elasticsearch is a powerful search and analytics engine that enables fast and efficient querying of large datasets. MongoDB in Graylog is used to store metadata about log data and manage the configuration and state of the system.

Graylog also has a web-based user interface that allows users to search and visualize log data, as well as manage system configuration and settings:

Figure 10.3 – Graylog logging system architecture

The architecture of this solution is pretty simple, as you can notice in the preceding diagram.

Sentry is an open source error tracking tool that helps developers monitor and fix errors in their applications. It allows developers to track errors and exceptions in real time, enabling them to quickly diagnose and fix issues before they become critical. Sentry supports multiple programming languages, including Python, Java, JavaScript, and Ruby, among others.

One of the key benefits of using Sentry is its ease of setup and integration. Sentry can be easily integrated with popular frameworks and platforms, such as Django, Flask, and Rails, among others. It also provides a range of plugins and integrations with third-party tools, such as Slack and GitHub, to help developers streamline their workflows and collaborate more effectively.

Sentry provides developers with detailed error reports that include information about the error, such as the stack trace, environment variables, and request parameters. This allows developers to quickly identify the cause of the error and take corrective action. Sentry also provides real-time notifications when errors occur, so developers can respond immediately.

Another benefit of using Sentry is its ability to analyze errors over time. Sentry allows developers to track error rates and identify patterns in error occurrence, making it easier to identify and address systemic issues in the application. This data can also be used to improve the overall performance and reliability of the application.

Sentry provides integration with Jira, which is a popular ticketing and issue-tracking system. The integration allows developers to create Jira issues directly from within Sentry, making it easier to manage and track issues that are discovered through Sentry.

To set up the integration, you will first need to create a Jira API token and configure the integration settings in Sentry. Once the integration is set up, you can create Jira issues directly from Sentry by clicking the Create JIRA issue button on the Error details page. This will automatically populate the Jira issue with relevant information about the error, such as the error message, stack trace, and request parameters. You can find detailed instructions on how to do it on the official documentation page here: https://docs.sentry.io/product/integrations/issue-tracking/jira/.

Sentry provides integrations with several other popular ticketing and issue-tracking systems, such as GitHub, Trello, Asana, Clubhouse, and PagerDuty, which allows you to trigger PagerDuty incidents directly from Sentry.

In this section, we have shown you several leading solutions that are both open source and suitable for self-hosting. Self-hosting may, however, not be what you are looking for, if you wish to lower the complexity of both deployment and maintenance. The next section will cover monitoring and logging software hosted for you by third-party companies.

SaaS monitoring solutions are the easiest (and most expensive) to use. In most cases, what you’ll need to do is install and configure a small daemon (agent) on your servers or inside a cluster. And there you go, all your monitoring data is visible within minutes. SaaS is great if your team doesn’t have the capacity to implement other solutions but your budget allows you to use one. Here are some more popular applications for handling your monitoring, tracing, and logging needs.

Datadog is a monitoring and analytics platform that provides visibility into the performance and health of applications, infrastructure, and networks. It was founded in 2010 by Olivier Pomel and Alexis Lê-Quôc and is headquartered in New York City, with offices around the world. According to Datadog’s financial report for the fiscal year 2021 (ending December 31, 2021), their total revenue was $2.065 billion, which represents a 60% increase from the previous year (fiscal year 2020).

Datadog’s platform integrates with more than 450 technologies, including cloud providers, databases, and containers, allowing users to collect and correlate data from across their entire technology stack. It provides real-time monitoring, alerting, and collaboration tools that enable teams to troubleshoot issues, optimize performance, and improve the user experience.

Datadog allows users to monitor the health and performance of their servers, containers, and cloud services, providing insights into CPU usage, memory utilization, network traffic, and more.

Datadog’s APM tools provide detailed insights into the performance of web applications, microservices, and other distributed systems, allowing users to identify and diagnose bottlenecks and issues.

Log management tools in Datadog enable users to collect, process, and analyze logs from across their entire infrastructure, helping to troubleshoot issues and identify trends.

And finally, Datadog security monitoring helps detect and respond to threats by analyzing network traffic, identifying anomalies, and integrating with security solutions.

Dashboarding in Datadog allows users to visualize and analyze data from their applications, infrastructure, and network in a centralized location. Users can create a dashboard in Datadog by clicking on the Create Dashboard button and selecting the type of dashboard they want to create (e.g., Infrastructure, APM, Log, or Custom). They can then add widgets to the dashboard and configure their settings. There are multiple automated dashboards available; for instance, if you start sending data from a Kubernetes cluster, Datadog will show a dashboard for that. You can find more detailed information about using dashboards on the Datadog documentation website: https://docs.datadoghq.com/getting_started/dashboards/.

Widgets are the building blocks of a dashboard in Datadog. They can display metrics, logs, traces, events, or custom data. To add a widget, users can click on the + button and select the type of widget they want to add. They can then configure the widget’s settings, such as selecting the data source, applying filters, and setting the time range. For instance, you can view an example dashboard for the nginx web server on the Datadog web page: https://www.datadoghq.com/dashboards/nginx-dashboard/.

In addition to displaying data on a dashboard, Datadog provides various tools for exploring and analyzing data, such as the query builder, Live Tail, and tracing. Users can use these tools to dive deeper into the data and troubleshoot issues.

New Relic is a cloud-based software analytics company that provides real-time insights into the performance of web and mobile applications. Founded in 2008 by Lew Cirne (a software engineer and entrepreneur with experience at companies such as Apple and Wily Technology), New Relic has become a leading player in the Application Performance Management (APM) market. The company is headquartered in San Francisco and has offices in a number of other cities around the world. New Relic went public in 2014 and is traded on the New York Stock Exchange under the symbol NEWR.

New Relic reported its 2021 fiscal year financial results in May 2021. According to the report, New Relic’s revenue for the full fiscal year 2021 was $600.8 million, which represents a 3% increase compared to the previous fiscal year.

It’s worth noting that New Relic experienced some challenges in fiscal year 2021, including the impact of the COVID-19 pandemic and a strategic shift to a new pricing model.

New Relic’s main purpose is to help companies optimize their application performance and identify issues before they become major problems. The platform provides real-time visibility into the entire application stack, from the frontend user interface to the backend infrastructure, allowing developers and operations teams to quickly identify bottlenecks and optimize performance.

New Relic’s APM solution offers a variety of features, including code-level visibility, transaction tracing, real-time monitoring, and alerting. The platform also provides insights into application dependencies, database performance, and user behavior.

In addition to APM, New Relic also offers a range of other products and services, including infrastructure monitoring, mobile APM, and browser monitoring.

Ruxit is a comprehensive APM solution that helps businesses identify and troubleshoot performance issues across complex distributed applications, microservices, and cloud-native environments. It was initially founded in 2012 as an independent company and was later acquired by Dynatrace in 2015, expanding Dynatrace’s APM capabilities.

One of the key features of Ruxit is its ability to provide end-to-end visibility into the performance of applications, including code-level diagnostics, user experience monitoring, and infrastructure monitoring. This means that it can help businesses quickly pinpoint the root cause of performance problems and identify opportunities for optimization.

Ruxit also has a range of other features designed to make monitoring and troubleshooting easier and more efficient. For example, it uses artificial intelligence and machine learning to automatically detect anomalies and performance degradations, alerting users in real time. It also provides a range of analytics and visualization tools to help users understand application performance trends and identify patterns over time.

In addition to its monitoring capabilities, Ruxit also provides a range of integrations with other tools and services commonly used in modern application environments. This includes integration with container orchestration platforms such as Kubernetes, as well as with popular application development frameworks and tools.

Splunk was founded in 2003 by Erik Swan, Rob Das, and Michael Baum in San Francisco, California. Since then, the company has grown significantly and is now a publicly traded company with a global presence. Splunk’s software solutions are used by organizations in various industries, including financial services, healthcare, government, and retail, to name a few.

Splunk, you guessed it, is a data analysis and monitoring software solution used to monitor, search, analyze, and visualize machine-generated data in real time. The software can gather and analyze data from various sources, including servers, applications, networks, and mobile devices, and provide insights into the performance and behavior of an organization’s IT infrastructure.

The main uses of Splunk include security monitoring, application monitoring, log management, and business analytics. With Splunk, users can identify security threats, troubleshoot application performance issues, monitor network activity, and gain insights into business operations.

One of the key features of Splunk is its ability to collect and analyze data from a wide range of sources, including structured and unstructured data. The software can also scale to handle large volumes of data, making it a powerful tool.

In this section, we have presented you with a few leading solutions hosted by third-party companies that are ready to use; they just require integration with your systems. In the next section, we are going to describe and explain retention policies for both logs and metrics.

Data retention refers to the practice of retaining data, or keeping data stored for a certain period of time. This can involve storing data on servers, hard drives, or other storage devices. The purpose of data retention is to ensure that data is available for future use or analysis.

Data retention policies are often developed by organizations to determine how long specific types of data should be retained. These policies may be driven by regulatory requirements, legal obligations, or business needs. For example, some regulations may require financial institutions to retain transaction data for a certain number of years, while businesses may choose to retain customer data for marketing or analytics purposes.

Data retention policies typically include guidelines for how data should be stored, how long it should be retained, and when it should be deleted. Effective data retention policies can help organizations to manage their data more efficiently, reduce storage costs, and ensure compliance with applicable regulations and laws.

When it comes to data retention strategies, organizations have a number of options to consider. Depending on the specific needs of the organization, different strategies may be more or less suitable.

In this strategy, all data is kept indefinitely. This is often used for compliance purposes, such as for regulatory requirements that mandate data retention for a specific period of time. This strategy can be expensive as it requires a large amount of storage, but it can also provide significant benefits in terms of historical analysis and trend spotting.

Time-based retention is a strategy where data is kept for a specific period of time before it is deleted. This strategy is often used to balance the need for data with storage costs. The retention period can be set based on regulatory requirements, business needs, or other factors.

Event-based retention is a strategy where data is kept based on specific events or triggers. For example, data may be retained for a specific customer or transaction, or based on the severity of an event. This strategy can help to reduce storage costs while still maintaining access to important data.

Selective retention is a strategy where only certain types of data are retained. This strategy can be used to prioritize the retention of the most important data while reducing storage costs. For example, an organization may choose to retain only data related to financial transactions or customer interactions.

Tiered retention is a strategy where data is stored in different tiers based on its age or importance. For example, recent data may be stored on fast, expensive storage, while older data is moved to slower, less expensive storage. This strategy can help to balance the need for fast access to recent data with the need to reduce storage costs over time.

Each of these data retention strategies has its own benefits and drawbacks, and the best strategy for an organization will depend on its specific needs and goals. It’s important to carefully consider the trade-offs between cost, storage capacity, and the value of the data being retained when choosing a data retention strategy.

The most common mistake in organizations is to use full retention strategies just in case, which often leads to exhausted disk space and increased cloud costs. Sometimes this strategy is justified, but not in most cases.

In this chapter, we covered the differences between monitoring, tracing, and logging. Monitoring is the process of observing and collecting data on a system to ensure it’s running correctly. Tracing is the process of tracking requests as they flow through a system to identify performance issues. Logging is the process of recording events and errors in a system for later analysis.

We also discussed cloud solutions for monitoring, logging, and tracing in Azure, GCP, and AWS. For Azure, we mentioned Azure Monitor for monitoring and Azure Application Insights for tracing. For AWS, we mentioned CloudWatch for monitoring and logging, and X-Ray for tracing.

We then went on to explain and provide an example of configuring the AWS CloudWatch agent on an EC2 instance. We also introduced AWS X-Ray with a code example to show how it can be used to trace requests in a distributed system.

Finally, we named some open source and SaaS solutions for monitoring, logging, and tracing, including Grafana, Prometheus, Datadog, New Relic, and Splunk. These solutions provide various features and capabilities for monitoring and troubleshooting systems, depending on the user’s requirements and preferences.

In the next chapter, we will get hands-on with automating server configuration with the use of a configuration as code solution: Ansible.