Sentry: Error Tracking and Monitoring
Sentry is a platform for error logging and application monitoring. The data we receive in Sentry contains comprehensive information about the context in which an issue occurred, making it easier to reproduce, trace the root cause, and significantly assist in error resolution. It's a valuable tool for developers, testers, and DevOps professionals. This open-source project can be deployed on a private or cloud server.
Originally, Sentry was a web interface for displaying traces and exceptions in an organized way, grouping them by type. Over time, it has grown, adding new features, capabilities, and integrations. It's impossible to showcase everything it can do in a single article fully, and even a brief video overview could take up to three hours.
Official Website
Documentation
GitHub
Why Use Sentry When We Have Logging?
Reviewing logs to understand what's happening with a service is helpful. When logs from all services are centralized in one place, like Elastic, OpenSearch, or Loki, it’s even better. However, you can analyze errors and exceptions faster, more conveniently, and with greater detail in Sentry. There are situations when log analysis alone does not clarify an issue, and Sentry comes to the rescue.
Consider cases where a user of your service fails to log in, buy a product, or perform some other action and leaves without submitting a support ticket. Such issues are extremely difficult to identify through logs alone. Even if a support ticket is submitted, analyzing, identifying, and reproducing such specific errors can be costly:
What device and browser were used?
What function triggered the error, and why? What specific error occurred?
What data was on the front end, and what was sent to the backend?
Sentry’s standout feature is the way it provides detailed contextual information about errors in an accessible format, enabling faster response and improved development.
As the project developers claim on their website, “Your code will tell you more than what logs reveal. Sentry’s full-stack monitoring shows a more complete picture of what's happening in your service’s code, helping identify issues before they lead to downtime.”
How It Works
In your application code, you set up a DSN (URL) for your Sentry platform, which serves as the destination for reports (errors, exceptions, and logs). You can also customize, extend, or mask the data being sent as needed.
Sentry supports JavaScript, Node, Python, PHP, Ruby, Java, and other programming languages.
In the setup screenshot, you can see various project types, such as a basic Python project as well as Django, Flask, and FastAPI frameworks. These frameworks offer enhanced and more detailed data configurations for report submission.
Usage Options
Sentry offers two main usage options:
Self-hosted (deployed on your own server)
Cloud-based (includes a limited free version and paid plans with monthly billing)
The Developer version is a free cloud plan suitable for getting acquainted with Sentry.
For anyone interested in Sentry, we recommend at least trying the free cloud version, as it’s a good introduction. However, a self-hosted option is ideal since the cloud version can experience error reporting delays of 1 to 5 minutes, which may be inconvenient.
Self-Hosted Version Installation
Now, let's move on to the technical part. To deploy Sentry self-hosted, we need the getsentry/self-hosted repository. The platform will be set up using Docker Compose.
System Requirements
Docker 19.03.6+
Docker Compose 2.19.0+
4 CPU cores
16 GB RAM
20 GB free disk space
We’ll be using a VPS from Hostman with Ubuntu 22.04.
System Setup
Update Dependencies
First, we need to update the system packages:
apt update && apt upgrade -y
Install Required Packages
Docker
Docker's version available in the repository is 24.0.7, so we’ll install it with:
apt install docker.io
Docker Compose
The version offered by apt is 1.29.2-1, which does not match the required version. So we need to install in manully. We’ll get the latest version directly from the official repository:
VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | grep -Po '"tag_name": "\K.*\d')DESTINATION=/usr/bin/docker-composesudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATIONsudo chmod 755 $DESTINATION
Verify Docker Compose Installation
To ensure everything is correctly installed, check the version of Docker Compose:
docker-compose --version
Output:
Docker Compose version v2.20.3
Once these steps are completed, you can proceed with deploying Sentry using Docker Compose.
Installation
The Sentry developers have simplified the installation process with a script. Here's how to set it up:
Clone the Repository and Release Branch
First, clone the repository and checkout the release branch:
git clone https://github.com/getsentry/self-hosted.gitcd self-hostedgit checkout 24.10.0
Run the Installation Script
Start the installation process by running the script with the following flags:
./install.sh --skip-user-prompt --no-report-self-hosted-issues
Flags explanation:
--skip-user-prompt: Skips the prompt for creating a user (we’ll create the user manually, which can be simpler).
--no-report-self-hosted-issues: Skips the prompt to send anonymous data to the Sentry developers from your host (this helps developers improve the product, but it uses some resources; decide if you want this enabled).
The script will check system requirements and download the Docker images (docker pull).
Start Sentry
Once the setup is complete, you’ll see a message with the command to run Sentry:
You're all done! Run the following command to get Sentry running:docker-compose up -d
Run the command to start Sentry:
docker-compose up -d
The Sentry web interface will now be available at your host's IP address on port 9000.
Before your first login, edit the ./sentry/config.yml configuration file and the line:
system.url-prefix: 'http://server_IP:9000'
And restart the containers:
docker-compose restart
Create a User
We skipped the user creation during the installation, so let’s create the user manually. Run:
docker-compose run --rm web createuser
Enter your email, password, and answer whether you want to give the user superuser privileges.
Upon first login, you’ll see an initial setup screen where you can specify:
The URL for your Sentry instance.
Email server settings for sending emails.
Whether to allow other users to self-register.
At this point, Sentry is ready to use. You can read more about the configuration here.
Configuration Files
Sentry’s main configuration files include:
.env./sentry/config.yml./sentry/sentry.conf.py
By default, 42 containers are launched, and we can customize settings in the configuration files.
Currently, it is not possible to reduce the number of containers due to the complex architecture of the system.
You can modify the .env file to disable some features.
For example, to disable the collection of private statistics, add this line to .env:
SENTRY_BEACON=False
You can also change the event retention period. By default, it is set to 90 days:
SENTRY_EVENT_RETENTION_DAYS=90
Database and Caching
Project data and user accounts are stored in PostgreSQL. If needed, you can easily configure your own database and Redis in the configuration files.
HTTPS Proxy Setup
To access the web interface securely, you need to set up an HTTPS reverse proxy. The Sentry documentation does not specify a particular reverse proxy, but you can choose any that fits your needs.
After configuring your reverse proxy, you will need to update the system.url-prefix in the config.yml file and adjust the SSL/TLS settings in sentry/sentry.conf.py.
Project Setup and Integration with Sentry
To set up and connect your first project with Sentry, follow these steps:
Create a New Project
In the Sentry web interface, click Add New Project and choose your platform.
After creating the project, Sentry will generate a unique DSN (Data Source Name), which you'll need to use in your application to send events to Sentry.
Configure the traces_sample_rate
Pay attention to the traces_sample_rate setting. It controls the percentage of events that are sent to Sentry. The default value is 1.0, which sends 100% of all events.
traces_sample_rate=1.0 # 100% of events will be sent
If you set it to 0.25, it will only send 25% of events, which can be useful to avoid overwhelming the platform with too many similar errors. You can adjust this value depending on your needs.
You can read more about additional parameters of the sentry_sdk in the official documentation.
Example Code with Custom Exception
Here’s an example script that integrates Sentry with a custom exception and function:
import sentry_sdk
sentry_sdk.init(
dsn="http://[email protected]:9000/3", # DSN from project creation
traces_sample_rate=1.0, # Send 100% of events
environment="production", # Set the runtime environment
release="my-app-1.0.0", # Specify the app version
send_default_pii=True, # Send Personally Identifiable Information (PII)
)
class MyException(Exception):
pass
def my_function(user, email):
raise MyException(f"User {user} ({email}) encountered an error.")
def create_user():
print("Creating a user...")
my_function('James', '[email protected]')
if __name__ == "__main__":
sentry_sdk.capture_message("Just a simple message") # Send a test message to Sentry
create_user() # Simulate the error
Run the Script
Run the Python script:
python main.py
This script will:
Initialize Sentry with your project’s DSN.
Capture a custom exception when calling my_function.
Send an example message to Sentry.
Check Results in Sentry
After running the script, you should see the following in Sentry:
The Just a simple message message will appear in the event stream.
The MyException that is raised in my_function will be captured as an error, and the details of the exception will be logged.
You can also view the captured exception, including the user information (user and email) and any other data you choose to send (such as stack traces, environment, etc.).
In Sentry, the tags displayed in the error reports include important contextual information that can help diagnose issues. These tags often show:
Environment Variable: This indicates the runtime environment of the application, such as "production", "development", or "staging". It helps you understand which environment the error occurred in.
Release Version: The version of your application that was running when the error occurred. This is particularly useful for identifying issues that might be specific to certain releases or versions of the application.
Hostname: The name of the server or machine where the error happened. This can be helpful when working in distributed systems or multiple server environments, as it shows the exact server where the issue occurred.
These tags appear in the error reports, providing valuable context about the circumstances surrounding the issue. For example, the stack trace might show which functions were involved in the error, and these tags can give you additional information, such as which version of the app was running and on which server, making it easier to trace and resolve issues.
Sentry automatically adds these contextual tags, but you can also customize them by passing additional information when you capture errors, such as environment, release version, or user-related data.
Conclusion
In this article, we discussed Sentry and how it can help track errors and monitor applications. We hope it has sparked your interest enough to explore the documentation or try out Sentry.
Despite being a comprehensive platform, Sentry is easy to install and configure. The key is to carefully manage errors and group events and use flexible configurations to avoid chaos. When set up properly, Sentry becomes a powerful and efficient tool for development teams, offering valuable insights into application behavior and performance.
15 November 2024 · 10 min to read