Sentry Error Tracking
Integrate the Sentry error and exception tracking platform into trading bot applications for real-time error monitoring with full stack traces, local variable state capture, contextual breadcrumb trails, and intelligent alert routing and deduplication for rapid incident response and root cause diagnosis.
Infrastructure Monitoring: Track Crypto Errors with Sentry
This notebook demonstrates how to integrate Sentry for robust error tracking in applications, with a specific focus on crypto-related operations. In the volatile and critical world of decentralized applications (dApps), exchanges, and blockchain services, effective error monitoring is paramount to ensure reliability, security, and a seamless user experience.
Sentry provides real-time error tracking and performance monitoring, enabling developers to quickly identify, diagnose, and resolve issues. By instrumenting our crypto applications with Sentry, we can gain deep insights into runtime errors, performance bottlenecks, and user-impacting problems, allowing for proactive maintenance and rapid incident response.
Concepts Covered
| Concept | Description |
|---|---|
| Sentry | An open-source error tracking and performance monitoring platform that helps developers monitor and fix crashes in real-time. |
| Error Tracking | The process of identifying, logging, and managing errors and exceptions that occur in a software application. Essential for maintaining application stability and reliability. |
| Crypto Applications | Software systems interacting with blockchain networks, cryptocurrencies, or decentralized finance (DeFi) protocols, such as wallets, exchanges, dApps, or trading bots. |
| DSN (Data Source Name) | A unique URL provided by Sentry for each project, used to configure the Sentry SDK and direct captured events to the correct project. |
| Breadcrumbs | A trail of events (e.g., user clicks, network requests, console logs) that occurred before an error, providing context to help reproduce and understand the issue. |
| Context (User, Tags, Extras) | Additional information attached to error events (e.g., user ID, transaction hash, specific environment variables) to enrich data and aid in debugging. |
Dependency Installation
This section installs all necessary Python packages required for the notebook, primarily sentry-sdk for error tracking, and other data manipulation/visualization libraries.
pip install sentry-sdk pandas matplotlib seabornRequirement already satisfied: sentry-sdk in /usr/local/lib/python3.12/dist-packages (2.61.1) Requirement already satisfied: pandas in /usr/local/lib/python3.12/dist-packages (2.2.2) Requirement already satisfied: matplotlib in /usr/local/lib/python3.12/dist-packages (3.10.0) Requirement already satisfied: seaborn in /usr/local/lib/python3.12/dist-packages (0.13.2) Requirement already satisfied: urllib3>=1.26.11 in /usr/local/lib/python3.12/dist-packages (from sentry-sdk) (2.5.0) Requirement already satisfied: certifi in /usr/local/lib/python3.12/dist-packages (from sentry-sdk) (2026.5.20) Requirement already satisfied: numpy>=1.26.0 in /usr/local/lib/python3.12/dist-packages (from pandas) (2.0.2) Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.12/dist-packages (from pandas) (2.9.0.post0) Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.2) Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.12/dist-packages (from pandas) (2026.2) Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.3.3) Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (0.12.1) Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (4.63.0) Requirement already satisfied: kiwisolver>=1.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.5.0) Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (26.2) Requirement already satisfied: pillow>=8 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (11.3.0) Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (3.3.2) Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.12/dist-packages (from python-dateutil>=2.8.2->pandas) (1.17.0)
Library Imports
This section imports all standard and third-party libraries used throughout the notebook.
import os
import logging
import random
import time
import functools
from collections import deque
import sentry_sdk
from sentry_sdk.integrations.logging import LoggingIntegration
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as snsCore Functions
This section defines the core functions required for our Sentry integration and crypto application simulation. Each function is presented in its own block, adhering to the specified documentation and coding style guidelines.
Function Name: create_app_state
This function initializes the application's state, returning a dictionary that holds various parameters and configurations. This includes an initial Sentry DSN, a logger instance, and other simulation-specific settings.
Parameters:
sentry_dsn(str): The Sentry Data Source Name for error reporting.log_level(str): The logging level for the application (e.g., 'INFO', 'DEBUG').
Returns:
dict: An initialized state dictionary for the application.
def create_app_state(sentry_dsn: str, log_level: str = 'INFO') -> dict:
"""
Initializes the application's state with all required metric keys.
"""
logger = logging.getLogger(__name__)
numeric_level = getattr(logging, log_level.upper(), logging.INFO)
logger.setLevel(numeric_level)
if not logger.handlers:
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
return {
'sentry_dsn': sentry_dsn,
'logger': logger,
'transaction_history': deque(maxlen=100),
'metrics': {
'errors_logged': 0,
'transactions_processed': 0,
'network_errors': 0,
'api_errors': 0,
'api_success': 0,
'sentry_capture_errors': 0
},
'app_status': 'running'
}Function Name: initialize_sentry
This function initializes the Sentry SDK with the provided DSN and other configurations. It sets up breadcrumbs, integrates with logging, and ensures proper error capture.
Parameters:
state(dict): The current application state dictionary, containing thesentry_dsnandlogger.
Returns:
dict: The updated state dictionary, confirming Sentry initialization.
def initialize_sentry(state: dict) -> dict:
"""
Initializes the Sentry SDK with the provided DSN and configurations.
Parameters
----------
state : dict
The current application state dictionary.
Returns
-------
dict
The updated state dictionary.
"""
logger = state['logger']
sentry_dsn = state['sentry_dsn']
if not sentry_dsn or sentry_dsn == "YOUR_SENTRY_DSN_HERE":
logger.warning("Sentry DSN is not set. Sentry will not be initialized.")
return state
try:
sentry_logging = LoggingIntegration(
level=logging.INFO, # Capture info and above as breadcrumbs
event_level=logging.ERROR # Send errors as events
)
sentry_sdk.init(
dsn=sentry_dsn,
traces_sample_rate=1.0,
environment="development",
release=f"crypto-monitor@{os.getenv('BUILD_VERSION', '1.0.0')}",
debug=False,
integrations=[sentry_logging]
)
logger.info(f"Sentry SDK initialized for project {sentry_dsn.split('/')[-1]}.")
except Exception as e:
logger.error(f"Failed to initialize Sentry SDK: {e}")
return stateFunction Name: _exponential_backoff_retry
This is a helper decorator function that implements an exponential backoff retry mechanism for functions that might fail due to transient issues, such as network problems or API rate limits. It includes random jitter to prevent thundering herd problems.
Parameters:
max_retries(int): The maximum number of retry attempts.base_delay(float): The initial delay in seconds before the first retry.exceptions_to_catch(tuple): A tuple of exception types to catch and retry upon.
Returns:
Callable: A decorator that applies the retry logic to the wrapped function.
import functools # Explicitly import for decorator usage
def _exponential_backoff_retry(
max_retries: int = 5,
base_delay: float = 1.0,
exceptions_to_catch: tuple = (Exception,)
) -> callable:
"""
A decorator that implements an exponential backoff retry mechanism with random jitter.
Parameters
----------
max_retries : int, optional
The maximum number of retry attempts, defaults to 5.
base_delay : float, optional
The initial delay in seconds before the first retry, defaults to 1.0.
exceptions_to_catch : tuple, optional
A tuple of exception types to catch and retry upon, defaults to (Exception,).
Returns
-------
callable
A decorator that applies the retry logic to the wrapped function.
"""
def decorator(func):
@functools.wraps(func)
def wrapper(state: dict, *args, **kwargs):
logger = state['logger']
for i in range(max_retries):
try:
return func(state, *args, **kwargs)
except exceptions_to_catch as e:
if i < max_retries - 1:
# Exponential backoff with random jitter
delay = base_delay * (2 ** i) + random.uniform(0, 0.5)
logger.warning(f"Attempt {i+1}/{max_retries} failed for {func.__name__}: {e}. Retrying in {delay:.2f}s...")
sentry_sdk.capture_exception(e)
time.sleep(delay)
else:
logger.error(f"All {max_retries} attempts failed for {func.__name__}. Last error: {e}")
raise # Re-raise the last exception after all retries
return wrapper
return decoratorFunction Name: update_metrics
This function updates the application's internal metrics, such as error counts and processed transaction counts. It's crucial for tracking the health and performance of the application.
Parameters:
state(dict): The current application state dictionary.metric_name(str): The name of the metric to update (e.g., 'errors_logged', 'transactions_processed').value(int): The value to add to the metric. Can be negative for decrements.
Returns:
dict: The updated state dictionary with modified metrics.
def update_metrics(state: dict, metric_name: str, value: int = 1) -> dict:
"""
Updates the application's internal metrics.
Parameters
----------
state : dict
The current application state dictionary.
metric_name : str
The name of the metric to update (e.g., 'errors_logged', 'transactions_processed').
value : int, optional
The value to add to the metric, defaults to 1.
Returns
-------
dict
The updated state dictionary with modified metrics.
"""
logger = state['logger']
if metric_name in state['metrics']:
state['metrics'][metric_name] += value
logger.debug(f"Metric '{metric_name}' updated to {state['metrics'][metric_name]}")
else:
logger.warning(f"Attempted to update unknown metric: '{metric_name}'")
state['metrics'][metric_name] = value # Initialize if not present
return stateFunction Name: simulate_crypto_transaction
This function simulates a cryptocurrency transaction, introducing a configurable chance of failure. When an error occurs, it captures the exception using Sentry and updates the application's error metrics. It also logs transaction details.
Parameters:
state(dict): The current application state dictionary.amount(float): The amount of cryptocurrency to transact.sender_address(str): The address of the sender.receiver_address(str): The address of the receiver.fail_chance(float): The probability (0.0 to 1.0) that the transaction will fail.
Returns:
dict: The updated state dictionary, including transaction history and metrics.
Raises:
ValueError: If the transaction fails based onfail_chanceor invalid amount.
@_exponential_backoff_retry(max_retries=3, base_delay=0.5, exceptions_to_catch=(ValueError, ConnectionError))
def simulate_crypto_transaction(state: dict, amount: float, sender_address: str, receiver_address: str, fail_chance: float = 0.2) -> dict:
"""
Simulates a cryptocurrency transaction with Sentry breadcrumbs.
"""
logger = state['logger']
transaction_id = f"TX-{time.time_ns()}"
sentry_sdk.add_breadcrumb(
category='transaction',
message=f'Attempting transaction {transaction_id}',
level='info',
data={'amount': amount, 'sender': sender_address, 'receiver': receiver_address}
)
if amount <= 0:
logger.error(f"Invalid amount: {amount}")
state = update_metrics(state, 'errors_logged')
raise ValueError("Transaction amount must be positive.")
if random.random() < fail_chance:
logger.error(f"Transaction {transaction_id} failed.")
state = update_metrics(state, 'errors_logged')
raise ValueError(f"Failure in transaction {transaction_id}")
transaction_details = {
'id': transaction_id,
'amount': amount,
'sender': sender_address,
'receiver': receiver_address,
'timestamp': pd.Timestamp.now(),
'status': 'success'
}
state['transaction_history'].append(transaction_details)
state = update_metrics(state, 'transactions_processed')
logger.info(f"Transaction {transaction_id} successful.")
return stateFunction Name: call_external_api
This function simulates a call to an external cryptocurrency exchange API. It includes a chance of failure to demonstrate error tracking for external dependencies. This function uses the _exponential_backoff_retry decorator to handle transient failures gracefully.
Parameters:
state(dict): The current application state dictionary.endpoint(str): The API endpoint being called (e.g., 'price_feed', 'order_book').params(dict): Parameters for the API call.fail_chance(float): Probability (0.0 to 1.0) of the API call failing.
Returns:
dict: An updated state dictionary (e.g., with metrics updated or API response stored).
Raises:
requests.exceptions.RequestException: If the API call fails.
Function Name: log_sentry_event
This function allows logging of arbitrary events to Sentry, not necessarily tied to an exception. This is useful for tracking specific application events, warnings, or informational messages within the Sentry dashboard.
Parameters:
state(dict): The current application state dictionary.message(str): The primary message for the event.level(str): The severity level of the event (e.g., 'info', 'warning', 'error', 'fatal').event_data(dict, optional): Additional context data to attach to the Sentry event.
Returns:
dict: The updated state dictionary.
def log_sentry_event(state: dict, message: str, level: str = 'info', event_data: dict = None) -> dict:
"""
Logs an arbitrary event to Sentry.
Parameters
----------
state : dict
The current application state dictionary.
message : str
The primary message for the event.
level : str, optional
The severity level of the event (e.g., 'info', 'warning', 'error', 'fatal'), defaults to 'info'.
event_data : dict, optional
Additional context data to attach to the Sentry event, defaults to None.
Returns
-------
dict
The updated state dictionary.
"""
logger = state['logger']
logger.debug(f"Logging Sentry event: {message} with level {level}")
try:
with sentry_sdk.push_scope() as scope:
scope.set_tag("custom_event", "true")
scope.set_tag("level", level)
if event_data:
for key, value in event_data.items():
scope.set_extra(key, value)
sentry_sdk.capture_message(message, level=level)
logger.info(f"Sentry event '{message}' captured successfully.")
except Exception as e:
logger.error(f"Failed to capture Sentry event '{message}': {e}")
state = update_metrics(state, 'sentry_capture_errors')
return stateFunction Name: generate_synthetic_transactions
This function generates a list of synthetic cryptocurrency transactions and attempts to process them using simulate_crypto_transaction. It's designed to create realistic data for demonstration purposes, including both successful and failed transactions.
Parameters:
state(dict): The current application state dictionary.num_transactions(int): The number of synthetic transactions to generate.base_fail_chance(float): The base probability of a transaction failing.
Returns:
dict: The updated state dictionary with processed transactions and metrics.
def generate_synthetic_transactions(state: dict, num_transactions: int, base_fail_chance: float = 0.2) -> dict:
"""
Generates and processes synthetic cryptocurrency transactions.
Parameters
----------
state : dict
The current application state dictionary.
num_transactions : int
The number of synthetic transactions to generate.
base_fail_chance : float, optional
The base probability of a transaction failing, defaults to 0.2.
Returns
-------
dict
The updated state dictionary with processed transactions and metrics.
"""
logger = state['logger']
logger.info(f"Generating {num_transactions} synthetic transactions...")
for i in range(num_transactions):
amount = round(random.uniform(0.001, 10), 4) # Crypto amount
sender = f"0x{os.urandom(20).hex()}"
receiver = f"0x{os.urandom(20).hex()}"
# Introduce some variability in fail chance
current_fail_chance = max(0, min(1, base_fail_chance + random.uniform(-0.1, 0.1)))
try:
state = simulate_crypto_transaction(state, amount, sender, receiver, fail_chance=current_fail_chance)
except (ValueError, ConnectionError) as e:
logger.warning(f"Synthetic transaction failed: {e}")
# Sentry already captures this from the simulate_crypto_transaction decorator
time.sleep(random.uniform(0.01, 0.1)) # Simulate some processing time
logger.info(f"Finished generating {num_transactions} synthetic transactions.")
return stateFunction Name: summarize_monitoring_data
This function analyzes the accumulated transaction history and metrics to provide a summary of the application's performance and error status. It can also create a pandas DataFrame for easier data manipulation and visualization.
Parameters:
state(dict): The current application state dictionary.
Returns:
pd.DataFrame: A DataFrame containing the transaction history.dict: A summary of aggregated metrics.
def summarize_monitoring_data(state: dict) -> tuple[pd.DataFrame, dict]:
"""
Analyzes and summarizes the accumulated transaction history and metrics.
"""
logger = state['logger']
if state['transaction_history']:
df_transactions = pd.DataFrame(list(state['transaction_history']))
else:
df_transactions = pd.DataFrame(columns=['id', 'amount', 'sender', 'receiver', 'timestamp', 'status'])
metrics_summary = {
'total_transactions': state['metrics'].get('transactions_processed', 0),
'total_errors': state['metrics'].get('errors_logged', 0),
'network_failures': state['metrics'].get('network_errors', 0),
'api_calls_failed': state['metrics'].get('api_errors', 0),
'api_calls_success': state['metrics'].get('api_success', 0),
'successful_transactions': len(df_transactions[df_transactions['status'] == 'success'])
}
return df_transactions, metrics_summaryDemonstration and Visualization
This section demonstrates the usage of the previously defined functions. We will set up the Sentry SDK, simulate various crypto-related operations including successful transactions, expected failures, and API call issues, and then visualize the collected monitoring data.
1. Setup: Initialize Application State and Sentry
We begin by creating the application state and initializing Sentry. Replace YOUR_SENTRY_DSN_HERE with your actual Sentry DSN. If you don't have one, you can still run the code, but Sentry events won't be sent.
import os # Explicitly import here for cell scope
# IMPORTANT: Replace with your actual Sentry DSN
SENTRY_DSN = os.getenv("SENTRY_DSN", "SENTRY_DSN_HERE")
# Initialize application state
app_state = create_app_state(sentry_dsn=SENTRY_DSN, log_level='DEBUG')
# Initialize Sentry SDK
app_state = initialize_sentry(app_state)
app_state['logger'].info("Application and Sentry initialized for demonstration.")2026-06-10 11:08:19,670 - __main__ - INFO - Sentry SDK initialized for project 4511540811005952. INFO:__main__:Sentry SDK initialized for project 4511540811005952. 2026-06-10 11:08:19,674 - __main__ - INFO - Application and Sentry initialized for demonstration. INFO:__main__:Application and Sentry initialized for demonstration.
2. Simulate Crypto Transactions (Success and Failure)
Here, we'll simulate individual crypto transactions. We'll show a successful one, one that fails due to ValueError (e.g., insufficient funds/invalid address), and one that fails due to a ConnectionError (e.g., network issue) to demonstrate the retry mechanism and Sentry capture.
app_state['logger'].info("--- Simulating individual crypto transactions ---")
# Successful transaction
try:
app_state = simulate_crypto_transaction(app_state, 0.5, '0x1A2B3C', '0x4D5E6F', fail_chance=0.0)
except (ValueError, ConnectionError):
pass # Expected to not fail
# Transaction with insufficient funds/invalid address (ValueError)
try:
app_state = simulate_crypto_transaction(app_state, 1.2, '0xAAABBB', '0xCCCDDD', fail_chance=1.0) # Force failure
except (ValueError, ConnectionError) as e:
app_state['logger'].error(f"Caught expected transaction error: {e}")
# Sentry will have captured this via the decorator
# Transaction with simulated network error (ConnectionError) to test retry
try:
app_state = simulate_crypto_transaction(app_state, 0.1, '0xEEEDDD', '0xFFFGGG', fail_chance=0.8) # High chance for network error
except (ValueError, ConnectionError) as e:
app_state['logger'].error(f"Caught expected transaction error after retries: {e}")
# Sentry will have captured this via the decorator after all retries
app_state['logger'].info("--- Individual crypto transaction simulation complete ---")2026-06-10 11:08:26,756 - __main__ - INFO - --- Simulating individual crypto transactions --- INFO:__main__:--- Simulating individual crypto transactions --- 2026-06-10 11:08:26,760 - __main__ - DEBUG - Metric 'transactions_processed' updated to 1 DEBUG:__main__:Metric 'transactions_processed' updated to 1 2026-06-10 11:08:26,762 - __main__ - INFO - Transaction TX-1781089706759978171 successful. INFO:__main__:Transaction TX-1781089706759978171 successful. 2026-06-10 11:08:26,765 - __main__ - ERROR - Transaction TX-1781089706765925568 failed. ERROR:__main__:Transaction TX-1781089706765925568 failed. 2026-06-10 11:08:26,783 - __main__ - DEBUG - Metric 'errors_logged' updated to 1 DEBUG:__main__:Metric 'errors_logged' updated to 1 2026-06-10 11:08:26,794 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089706765925568. Retrying in 0.97s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089706765925568. Retrying in 0.97s... 2026-06-10 11:08:27,807 - __main__ - ERROR - Transaction TX-1781089707807307820 failed. ERROR:__main__:Transaction TX-1781089707807307820 failed. 2026-06-10 11:08:27,814 - __main__ - DEBUG - Metric 'errors_logged' updated to 2 DEBUG:__main__:Metric 'errors_logged' updated to 2 2026-06-10 11:08:27,820 - __main__ - WARNING - Attempt 2/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089707807307820. Retrying in 1.14s... WARNING:__main__:Attempt 2/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089707807307820. Retrying in 1.14s... 2026-06-10 11:08:28,972 - __main__ - ERROR - Transaction TX-1781089708972786068 failed. ERROR:__main__:Transaction TX-1781089708972786068 failed. 2026-06-10 11:08:28,979 - __main__ - DEBUG - Metric 'errors_logged' updated to 3 DEBUG:__main__:Metric 'errors_logged' updated to 3 2026-06-10 11:08:28,985 - __main__ - ERROR - All 3 attempts failed for simulate_crypto_transaction. Last error: Failure in transaction TX-1781089708972786068 ERROR:__main__:All 3 attempts failed for simulate_crypto_transaction. Last error: Failure in transaction TX-1781089708972786068 2026-06-10 11:08:28,991 - __main__ - ERROR - Caught expected transaction error: Failure in transaction TX-1781089708972786068 ERROR:__main__:Caught expected transaction error: Failure in transaction TX-1781089708972786068 2026-06-10 11:08:28,999 - __main__ - ERROR - Transaction TX-1781089708999608904 failed. ERROR:__main__:Transaction TX-1781089708999608904 failed. 2026-06-10 11:08:29,006 - __main__ - DEBUG - Metric 'errors_logged' updated to 4 DEBUG:__main__:Metric 'errors_logged' updated to 4 2026-06-10 11:08:29,008 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089708999608904. Retrying in 0.79s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089708999608904. Retrying in 0.79s... 2026-06-10 11:08:29,806 - __main__ - ERROR - Transaction TX-1781089709806654881 failed. ERROR:__main__:Transaction TX-1781089709806654881 failed. 2026-06-10 11:08:29,815 - __main__ - DEBUG - Metric 'errors_logged' updated to 5 DEBUG:__main__:Metric 'errors_logged' updated to 5 2026-06-10 11:08:29,818 - __main__ - WARNING - Attempt 2/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089709806654881. Retrying in 1.14s... WARNING:__main__:Attempt 2/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089709806654881. Retrying in 1.14s... 2026-06-10 11:08:30,967 - __main__ - ERROR - Transaction TX-1781089710967080339 failed. ERROR:__main__:Transaction TX-1781089710967080339 failed. 2026-06-10 11:08:30,974 - __main__ - DEBUG - Metric 'errors_logged' updated to 6 DEBUG:__main__:Metric 'errors_logged' updated to 6 2026-06-10 11:08:30,979 - __main__ - ERROR - All 3 attempts failed for simulate_crypto_transaction. Last error: Failure in transaction TX-1781089710967080339 ERROR:__main__:All 3 attempts failed for simulate_crypto_transaction. Last error: Failure in transaction TX-1781089710967080339 2026-06-10 11:08:30,986 - __main__ - ERROR - Caught expected transaction error after retries: Failure in transaction TX-1781089710967080339 ERROR:__main__:Caught expected transaction error after retries: Failure in transaction TX-1781089710967080339 2026-06-10 11:08:30,994 - __main__ - INFO - --- Individual crypto transaction simulation complete --- INFO:__main__:--- Individual crypto transaction simulation complete ---
3. Simulate External API Calls (Success and Failure with Retries)
We'll demonstrate calling an external API with varying fail_chance to observe the retry mechanism and how Sentry captures these issues.
app_state['logger'].info("--- Starting Simulation --- ")
# 1. API Call Demonstration
try:
app_state = call_external_api(app_state, 'price_feed', {'symbol': 'BTC/USD'})
except Exception:
pass
# 2. Transaction Demonstration
try:
app_state = simulate_crypto_transaction(app_state, 0.5, '0xABC', '0xDEF')
except Exception:
pass
# 3. Batch Simulation
app_state = generate_synthetic_transactions(app_state, 10)
# 4. Final Summarization
df_results, metrics = summarize_monitoring_data(app_state)
display(df_results.head())
print(f"Final Metrics: {metrics}")2026-06-10 11:08:41,171 - __main__ - INFO - --- Starting Simulation --- INFO:__main__:--- Starting Simulation --- 2026-06-10 11:08:41,173 - __main__ - INFO - API call to price_feed successful. INFO:__main__:API call to price_feed successful. 2026-06-10 11:08:41,176 - __main__ - DEBUG - Metric 'api_success' updated to 1 DEBUG:__main__:Metric 'api_success' updated to 1 2026-06-10 11:08:41,179 - __main__ - DEBUG - Metric 'transactions_processed' updated to 2 DEBUG:__main__:Metric 'transactions_processed' updated to 2 2026-06-10 11:08:41,181 - __main__ - INFO - Transaction TX-1781089721178904135 successful. INFO:__main__:Transaction TX-1781089721178904135 successful. 2026-06-10 11:08:41,183 - __main__ - INFO - Generating 10 synthetic transactions... INFO:__main__:Generating 10 synthetic transactions... 2026-06-10 11:08:41,185 - __main__ - DEBUG - Metric 'transactions_processed' updated to 3 DEBUG:__main__:Metric 'transactions_processed' updated to 3 2026-06-10 11:08:41,188 - __main__ - INFO - Transaction TX-1781089721185528055 successful. INFO:__main__:Transaction TX-1781089721185528055 successful. 2026-06-10 11:08:41,282 - __main__ - DEBUG - Metric 'transactions_processed' updated to 4 DEBUG:__main__:Metric 'transactions_processed' updated to 4 2026-06-10 11:08:41,284 - __main__ - INFO - Transaction TX-1781089721282733925 successful. INFO:__main__:Transaction TX-1781089721282733925 successful. 2026-06-10 11:08:41,361 - __main__ - DEBUG - Metric 'transactions_processed' updated to 5 DEBUG:__main__:Metric 'transactions_processed' updated to 5 2026-06-10 11:08:41,363 - __main__ - INFO - Transaction TX-1781089721361625022 successful. INFO:__main__:Transaction TX-1781089721361625022 successful. 2026-06-10 11:08:41,393 - __main__ - DEBUG - Metric 'transactions_processed' updated to 6 DEBUG:__main__:Metric 'transactions_processed' updated to 6 2026-06-10 11:08:41,395 - __main__ - INFO - Transaction TX-1781089721393376268 successful. INFO:__main__:Transaction TX-1781089721393376268 successful. 2026-06-10 11:08:41,470 - __main__ - DEBUG - Metric 'transactions_processed' updated to 7 DEBUG:__main__:Metric 'transactions_processed' updated to 7 2026-06-10 11:08:41,472 - __main__ - INFO - Transaction TX-1781089721470140185 successful. INFO:__main__:Transaction TX-1781089721470140185 successful. 2026-06-10 11:08:41,553 - __main__ - DEBUG - Metric 'transactions_processed' updated to 8 DEBUG:__main__:Metric 'transactions_processed' updated to 8 2026-06-10 11:08:41,555 - __main__ - INFO - Transaction TX-1781089721553513688 successful. INFO:__main__:Transaction TX-1781089721553513688 successful. 2026-06-10 11:08:41,580 - __main__ - DEBUG - Metric 'transactions_processed' updated to 9 DEBUG:__main__:Metric 'transactions_processed' updated to 9 2026-06-10 11:08:41,582 - __main__ - INFO - Transaction TX-1781089721580724977 successful. INFO:__main__:Transaction TX-1781089721580724977 successful. 2026-06-10 11:08:41,645 - __main__ - ERROR - Transaction TX-1781089721645855368 failed. ERROR:__main__:Transaction TX-1781089721645855368 failed. 2026-06-10 11:08:41,653 - __main__ - DEBUG - Metric 'errors_logged' updated to 7 DEBUG:__main__:Metric 'errors_logged' updated to 7 2026-06-10 11:08:41,656 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089721645855368. Retrying in 0.55s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089721645855368. Retrying in 0.55s... 2026-06-10 11:08:42,218 - __main__ - DEBUG - Metric 'transactions_processed' updated to 10 DEBUG:__main__:Metric 'transactions_processed' updated to 10 2026-06-10 11:08:42,222 - __main__ - INFO - Transaction TX-1781089722218361506 successful. INFO:__main__:Transaction TX-1781089722218361506 successful. 2026-06-10 11:08:42,263 - __main__ - DEBUG - Metric 'transactions_processed' updated to 11 DEBUG:__main__:Metric 'transactions_processed' updated to 11 2026-06-10 11:08:42,264 - __main__ - INFO - Transaction TX-1781089722262979130 successful. INFO:__main__:Transaction TX-1781089722262979130 successful. 2026-06-10 11:08:42,317 - __main__ - DEBUG - Metric 'transactions_processed' updated to 12 DEBUG:__main__:Metric 'transactions_processed' updated to 12 2026-06-10 11:08:42,319 - __main__ - INFO - Transaction TX-1781089722317297915 successful. INFO:__main__:Transaction TX-1781089722317297915 successful. 2026-06-10 11:08:42,354 - __main__ - INFO - Finished generating 10 synthetic transactions. INFO:__main__:Finished generating 10 synthetic transactions.
| id | amount | sender | receiver | timestamp | status | |
|---|---|---|---|---|---|---|
| 0 | TX-1781089706759978171 | 0.5000 | 0x1A2B3C | 0x4D5E6F | 2026-06-10 11:08:26.760027 | success |
| 1 | TX-1781089721178904135 | 0.5000 | 0xABC | 0xDEF | 2026-06-10 11:08:41.178951 | success |
| 2 | TX-1781089721185528055 | 5.9284 | 0x14fbcd69854a23a444ae5f320728904f4cfc1d03 | 0x28fc5dbabbcf97c11adb3be8e5d06059de321731 | 2026-06-10 11:08:41.185562 | success |
| 3 | TX-1781089721282733925 | 7.0603 | 0x8fc84058d2045979a767619270398df772cf5886 | 0x924117f51c160dd2d5cf3d698f623d246238e70f | 2026-06-10 11:08:41.282794 | success |
| 4 | TX-1781089721361625022 | 0.8937 | 0x0a654acf4df1135c39c931e6e335c2629670a4d0 | 0x39e2b5af85fea2e75ee3dc243373ea893ae0d3a9 | 2026-06-10 11:08:41.361678 | success |
Final Metrics: {'total_transactions': 12, 'total_errors': 7, 'network_failures': 0, 'api_calls_failed': 0, 'api_calls_success': 1, 'successful_transactions': 12}
4. Log Custom Sentry Events
Demonstrate logging a custom informational event and a warning event directly to Sentry.
app_state['logger'].info("--- Logging custom Sentry events ---")
app_state = log_sentry_event(app_state, "Maintenance window starting soon", level='info', event_data={'scheduled_for': '2023-12-31T23:00:00Z'})
app_state = log_sentry_event(app_state, "High transaction volume detected", level='warning', event_data={'tps': 1200, 'threshold': 1000})
app_state['logger'].info("--- Custom Sentry events logged ---")2026-06-10 11:08:53,760 - __main__ - INFO - --- Logging custom Sentry events --- INFO:__main__:--- Logging custom Sentry events --- 2026-06-10 11:08:53,762 - __main__ - DEBUG - Logging Sentry event: Maintenance window starting soon with level info DEBUG:__main__:Logging Sentry event: Maintenance window starting soon with level info /tmp/ipykernel_4665/3229019631.py:25: DeprecationWarning: sentry_sdk.push_scope is deprecated and will be removed in the next major version. Please consult our migration guide to learn how to migrate to the new API: https://docs.sentry.io/platforms/python/migration/1.x-to-2.x#scope-pushing with sentry_sdk.push_scope() as scope: 2026-06-10 11:08:53,772 - __main__ - INFO - Sentry event 'Maintenance window starting soon' captured successfully. INFO:__main__:Sentry event 'Maintenance window starting soon' captured successfully. 2026-06-10 11:08:53,778 - __main__ - DEBUG - Logging Sentry event: High transaction volume detected with level warning DEBUG:__main__:Logging Sentry event: High transaction volume detected with level warning 2026-06-10 11:08:53,786 - __main__ - INFO - Sentry event 'High transaction volume detected' captured successfully. INFO:__main__:Sentry event 'High transaction volume detected' captured successfully. 2026-06-10 11:08:53,791 - __main__ - INFO - --- Custom Sentry events logged --- INFO:__main__:--- Custom Sentry events logged ---
5. Generate and Process a Batch of Synthetic Transactions
To get a larger dataset for visualization, we'll generate many synthetic transactions with a defined failure rate.
app_state['logger'].info("--- Generating a batch of synthetic transactions ---")
NUM_BATCH_TRANSACTIONS = 50
app_state = generate_synthetic_transactions(app_state, NUM_BATCH_TRANSACTIONS, base_fail_chance=0.3)
app_state['logger'].info("--- Batch of synthetic transactions complete ---")2026-06-10 11:09:05,494 - __main__ - INFO - --- Generating a batch of synthetic transactions --- INFO:__main__:--- Generating a batch of synthetic transactions --- 2026-06-10 11:09:05,499 - __main__ - INFO - Generating 50 synthetic transactions... INFO:__main__:Generating 50 synthetic transactions... 2026-06-10 11:09:05,502 - __main__ - DEBUG - Metric 'transactions_processed' updated to 13 DEBUG:__main__:Metric 'transactions_processed' updated to 13 2026-06-10 11:09:05,503 - __main__ - INFO - Transaction TX-1781089745502157753 successful. INFO:__main__:Transaction TX-1781089745502157753 successful. 2026-06-10 11:09:05,584 - __main__ - DEBUG - Metric 'transactions_processed' updated to 14 DEBUG:__main__:Metric 'transactions_processed' updated to 14 2026-06-10 11:09:05,587 - __main__ - INFO - Transaction TX-1781089745584459388 successful. INFO:__main__:Transaction TX-1781089745584459388 successful. 2026-06-10 11:09:05,685 - __main__ - DEBUG - Metric 'transactions_processed' updated to 15 DEBUG:__main__:Metric 'transactions_processed' updated to 15 2026-06-10 11:09:05,687 - __main__ - INFO - Transaction TX-1781089745685293036 successful. INFO:__main__:Transaction TX-1781089745685293036 successful. 2026-06-10 11:09:05,720 - __main__ - DEBUG - Metric 'transactions_processed' updated to 16 DEBUG:__main__:Metric 'transactions_processed' updated to 16 2026-06-10 11:09:05,722 - __main__ - INFO - Transaction TX-1781089745720647494 successful. INFO:__main__:Transaction TX-1781089745720647494 successful. 2026-06-10 11:09:05,747 - __main__ - DEBUG - Metric 'transactions_processed' updated to 17 DEBUG:__main__:Metric 'transactions_processed' updated to 17 2026-06-10 11:09:05,750 - __main__ - INFO - Transaction TX-1781089745747630916 successful. INFO:__main__:Transaction TX-1781089745747630916 successful. 2026-06-10 11:09:05,792 - __main__ - ERROR - Transaction TX-1781089745792743773 failed. ERROR:__main__:Transaction TX-1781089745792743773 failed. 2026-06-10 11:09:05,802 - __main__ - DEBUG - Metric 'errors_logged' updated to 8 DEBUG:__main__:Metric 'errors_logged' updated to 8 2026-06-10 11:09:05,805 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089745792743773. Retrying in 0.99s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089745792743773. Retrying in 0.99s... 2026-06-10 11:09:06,810 - __main__ - DEBUG - Metric 'transactions_processed' updated to 18 DEBUG:__main__:Metric 'transactions_processed' updated to 18 2026-06-10 11:09:06,813 - __main__ - INFO - Transaction TX-1781089746810496191 successful. INFO:__main__:Transaction TX-1781089746810496191 successful. 2026-06-10 11:09:06,878 - __main__ - ERROR - Transaction TX-1781089746878091729 failed. ERROR:__main__:Transaction TX-1781089746878091729 failed. 2026-06-10 11:09:06,887 - __main__ - DEBUG - Metric 'errors_logged' updated to 9 DEBUG:__main__:Metric 'errors_logged' updated to 9 2026-06-10 11:09:06,889 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089746878091729. Retrying in 0.82s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089746878091729. Retrying in 0.82s... 2026-06-10 11:09:07,722 - __main__ - DEBUG - Metric 'transactions_processed' updated to 19 DEBUG:__main__:Metric 'transactions_processed' updated to 19 2026-06-10 11:09:07,724 - __main__ - INFO - Transaction TX-1781089747722605241 successful. INFO:__main__:Transaction TX-1781089747722605241 successful. 2026-06-10 11:09:07,809 - __main__ - DEBUG - Metric 'transactions_processed' updated to 20 DEBUG:__main__:Metric 'transactions_processed' updated to 20 2026-06-10 11:09:07,811 - __main__ - INFO - Transaction TX-1781089747808954113 successful. INFO:__main__:Transaction TX-1781089747808954113 successful. 2026-06-10 11:09:07,843 - __main__ - DEBUG - Metric 'transactions_processed' updated to 21 DEBUG:__main__:Metric 'transactions_processed' updated to 21 2026-06-10 11:09:07,845 - __main__ - INFO - Transaction TX-1781089747843746955 successful. INFO:__main__:Transaction TX-1781089747843746955 successful. 2026-06-10 11:09:07,945 - __main__ - DEBUG - Metric 'transactions_processed' updated to 22 DEBUG:__main__:Metric 'transactions_processed' updated to 22 2026-06-10 11:09:07,947 - __main__ - INFO - Transaction TX-1781089747945414769 successful. INFO:__main__:Transaction TX-1781089747945414769 successful. 2026-06-10 11:09:08,026 - __main__ - DEBUG - Metric 'transactions_processed' updated to 23 DEBUG:__main__:Metric 'transactions_processed' updated to 23 2026-06-10 11:09:08,028 - __main__ - INFO - Transaction TX-1781089748026430632 successful. INFO:__main__:Transaction TX-1781089748026430632 successful. 2026-06-10 11:09:08,110 - __main__ - DEBUG - Metric 'transactions_processed' updated to 24 DEBUG:__main__:Metric 'transactions_processed' updated to 24 2026-06-10 11:09:08,112 - __main__ - INFO - Transaction TX-1781089748110165791 successful. INFO:__main__:Transaction TX-1781089748110165791 successful. 2026-06-10 11:09:08,197 - __main__ - ERROR - Transaction TX-1781089748197262099 failed. ERROR:__main__:Transaction TX-1781089748197262099 failed. 2026-06-10 11:09:08,207 - __main__ - DEBUG - Metric 'errors_logged' updated to 10 DEBUG:__main__:Metric 'errors_logged' updated to 10 2026-06-10 11:09:08,210 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089748197262099. Retrying in 0.51s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089748197262099. Retrying in 0.51s... 2026-06-10 11:09:08,733 - __main__ - DEBUG - Metric 'transactions_processed' updated to 25 DEBUG:__main__:Metric 'transactions_processed' updated to 25 2026-06-10 11:09:08,735 - __main__ - INFO - Transaction TX-1781089748733220960 successful. INFO:__main__:Transaction TX-1781089748733220960 successful. 2026-06-10 11:09:08,747 - __main__ - DEBUG - Metric 'transactions_processed' updated to 26 DEBUG:__main__:Metric 'transactions_processed' updated to 26 2026-06-10 11:09:08,750 - __main__ - INFO - Transaction TX-1781089748747855403 successful. INFO:__main__:Transaction TX-1781089748747855403 successful. 2026-06-10 11:09:08,774 - __main__ - ERROR - Transaction TX-1781089748774840850 failed. ERROR:__main__:Transaction TX-1781089748774840850 failed. 2026-06-10 11:09:08,787 - __main__ - DEBUG - Metric 'errors_logged' updated to 11 DEBUG:__main__:Metric 'errors_logged' updated to 11 2026-06-10 11:09:08,793 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089748774840850. Retrying in 0.68s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089748774840850. Retrying in 0.68s... 2026-06-10 11:09:09,491 - __main__ - DEBUG - Metric 'transactions_processed' updated to 27 DEBUG:__main__:Metric 'transactions_processed' updated to 27 2026-06-10 11:09:09,494 - __main__ - INFO - Transaction TX-1781089749491782518 successful. INFO:__main__:Transaction TX-1781089749491782518 successful. 2026-06-10 11:09:09,544 - __main__ - ERROR - Transaction TX-1781089749544019092 failed. ERROR:__main__:Transaction TX-1781089749544019092 failed. 2026-06-10 11:09:09,555 - __main__ - DEBUG - Metric 'errors_logged' updated to 12 DEBUG:__main__:Metric 'errors_logged' updated to 12 2026-06-10 11:09:09,560 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089749544019092. Retrying in 0.50s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089749544019092. Retrying in 0.50s... 2026-06-10 11:09:10,073 - __main__ - ERROR - Transaction TX-1781089750073848081 failed. ERROR:__main__:Transaction TX-1781089750073848081 failed. 2026-06-10 11:09:10,087 - __main__ - DEBUG - Metric 'errors_logged' updated to 13 DEBUG:__main__:Metric 'errors_logged' updated to 13 2026-06-10 11:09:10,092 - __main__ - WARNING - Attempt 2/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089750073848081. Retrying in 1.09s... WARNING:__main__:Attempt 2/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089750073848081. Retrying in 1.09s... 2026-06-10 11:09:11,195 - __main__ - DEBUG - Metric 'transactions_processed' updated to 28 DEBUG:__main__:Metric 'transactions_processed' updated to 28 2026-06-10 11:09:11,197 - __main__ - INFO - Transaction TX-1781089751195567276 successful. INFO:__main__:Transaction TX-1781089751195567276 successful. 2026-06-10 11:09:11,246 - __main__ - DEBUG - Metric 'transactions_processed' updated to 29 DEBUG:__main__:Metric 'transactions_processed' updated to 29 2026-06-10 11:09:11,249 - __main__ - INFO - Transaction TX-1781089751246873852 successful. INFO:__main__:Transaction TX-1781089751246873852 successful. 2026-06-10 11:09:11,280 - __main__ - DEBUG - Metric 'transactions_processed' updated to 30 DEBUG:__main__:Metric 'transactions_processed' updated to 30 2026-06-10 11:09:11,283 - __main__ - INFO - Transaction TX-1781089751280440529 successful. INFO:__main__:Transaction TX-1781089751280440529 successful. 2026-06-10 11:09:11,306 - __main__ - ERROR - Transaction TX-1781089751306448707 failed. ERROR:__main__:Transaction TX-1781089751306448707 failed. 2026-06-10 11:09:11,321 - __main__ - DEBUG - Metric 'errors_logged' updated to 14 DEBUG:__main__:Metric 'errors_logged' updated to 14 2026-06-10 11:09:11,325 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089751306448707. Retrying in 0.77s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089751306448707. Retrying in 0.77s... 2026-06-10 11:09:12,118 - __main__ - ERROR - Transaction TX-1781089752118310203 failed. ERROR:__main__:Transaction TX-1781089752118310203 failed. 2026-06-10 11:09:12,129 - __main__ - DEBUG - Metric 'errors_logged' updated to 15 DEBUG:__main__:Metric 'errors_logged' updated to 15 2026-06-10 11:09:12,136 - __main__ - WARNING - Attempt 2/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089752118310203. Retrying in 1.02s... WARNING:__main__:Attempt 2/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089752118310203. Retrying in 1.02s... 2026-06-10 11:09:13,173 - __main__ - DEBUG - Metric 'transactions_processed' updated to 31 DEBUG:__main__:Metric 'transactions_processed' updated to 31 2026-06-10 11:09:13,176 - __main__ - INFO - Transaction TX-1781089753173637795 successful. INFO:__main__:Transaction TX-1781089753173637795 successful. 2026-06-10 11:09:13,267 - __main__ - ERROR - Transaction TX-1781089753267743319 failed. ERROR:__main__:Transaction TX-1781089753267743319 failed. 2026-06-10 11:09:13,285 - __main__ - DEBUG - Metric 'errors_logged' updated to 16 DEBUG:__main__:Metric 'errors_logged' updated to 16 2026-06-10 11:09:13,291 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089753267743319. Retrying in 1.00s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089753267743319. Retrying in 1.00s... 2026-06-10 11:09:14,312 - __main__ - ERROR - Transaction TX-1781089754312236750 failed. ERROR:__main__:Transaction TX-1781089754312236750 failed. 2026-06-10 11:09:14,326 - __main__ - DEBUG - Metric 'errors_logged' updated to 17 DEBUG:__main__:Metric 'errors_logged' updated to 17 2026-06-10 11:09:14,332 - __main__ - WARNING - Attempt 2/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089754312236750. Retrying in 1.39s... WARNING:__main__:Attempt 2/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089754312236750. Retrying in 1.39s... 2026-06-10 11:09:15,744 - __main__ - ERROR - Transaction TX-1781089755744797665 failed. ERROR:__main__:Transaction TX-1781089755744797665 failed. 2026-06-10 11:09:15,756 - __main__ - DEBUG - Metric 'errors_logged' updated to 18 DEBUG:__main__:Metric 'errors_logged' updated to 18 2026-06-10 11:09:15,759 - __main__ - ERROR - All 3 attempts failed for simulate_crypto_transaction. Last error: Failure in transaction TX-1781089755744797665 ERROR:__main__:All 3 attempts failed for simulate_crypto_transaction. Last error: Failure in transaction TX-1781089755744797665 2026-06-10 11:09:15,770 - __main__ - WARNING - Synthetic transaction failed: Failure in transaction TX-1781089755744797665 WARNING:__main__:Synthetic transaction failed: Failure in transaction TX-1781089755744797665 2026-06-10 11:09:15,850 - __main__ - DEBUG - Metric 'transactions_processed' updated to 32 DEBUG:__main__:Metric 'transactions_processed' updated to 32 2026-06-10 11:09:15,852 - __main__ - INFO - Transaction TX-1781089755849863622 successful. INFO:__main__:Transaction TX-1781089755849863622 successful. 2026-06-10 11:09:15,942 - __main__ - DEBUG - Metric 'transactions_processed' updated to 33 DEBUG:__main__:Metric 'transactions_processed' updated to 33 2026-06-10 11:09:15,945 - __main__ - INFO - Transaction TX-1781089755942840423 successful. INFO:__main__:Transaction TX-1781089755942840423 successful. 2026-06-10 11:09:15,996 - __main__ - ERROR - Transaction TX-1781089755996379796 failed. ERROR:__main__:Transaction TX-1781089755996379796 failed. 2026-06-10 11:09:16,008 - __main__ - DEBUG - Metric 'errors_logged' updated to 19 DEBUG:__main__:Metric 'errors_logged' updated to 19 2026-06-10 11:09:16,010 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089755996379796. Retrying in 0.58s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089755996379796. Retrying in 0.58s... 2026-06-10 11:09:16,605 - __main__ - DEBUG - Metric 'transactions_processed' updated to 34 DEBUG:__main__:Metric 'transactions_processed' updated to 34 2026-06-10 11:09:16,608 - __main__ - INFO - Transaction TX-1781089756604815202 successful. INFO:__main__:Transaction TX-1781089756604815202 successful. 2026-06-10 11:09:16,666 - __main__ - DEBUG - Metric 'transactions_processed' updated to 35 DEBUG:__main__:Metric 'transactions_processed' updated to 35 2026-06-10 11:09:16,670 - __main__ - INFO - Transaction TX-1781089756666659510 successful. INFO:__main__:Transaction TX-1781089756666659510 successful. 2026-06-10 11:09:16,763 - __main__ - DEBUG - Metric 'transactions_processed' updated to 36 DEBUG:__main__:Metric 'transactions_processed' updated to 36 2026-06-10 11:09:16,766 - __main__ - INFO - Transaction TX-1781089756763552659 successful. INFO:__main__:Transaction TX-1781089756763552659 successful. 2026-06-10 11:09:16,781 - __main__ - ERROR - Transaction TX-1781089756781268466 failed. ERROR:__main__:Transaction TX-1781089756781268466 failed. 2026-06-10 11:09:16,792 - __main__ - DEBUG - Metric 'errors_logged' updated to 20 DEBUG:__main__:Metric 'errors_logged' updated to 20 2026-06-10 11:09:16,795 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089756781268466. Retrying in 0.85s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089756781268466. Retrying in 0.85s... 2026-06-10 11:09:17,663 - __main__ - DEBUG - Metric 'transactions_processed' updated to 37 DEBUG:__main__:Metric 'transactions_processed' updated to 37 2026-06-10 11:09:17,666 - __main__ - INFO - Transaction TX-1781089757663368305 successful. INFO:__main__:Transaction TX-1781089757663368305 successful. 2026-06-10 11:09:17,706 - __main__ - DEBUG - Metric 'transactions_processed' updated to 38 DEBUG:__main__:Metric 'transactions_processed' updated to 38 2026-06-10 11:09:17,709 - __main__ - INFO - Transaction TX-1781089757706502974 successful. INFO:__main__:Transaction TX-1781089757706502974 successful. 2026-06-10 11:09:17,736 - __main__ - DEBUG - Metric 'transactions_processed' updated to 39 DEBUG:__main__:Metric 'transactions_processed' updated to 39 2026-06-10 11:09:17,738 - __main__ - INFO - Transaction TX-1781089757736216375 successful. INFO:__main__:Transaction TX-1781089757736216375 successful. 2026-06-10 11:09:17,806 - __main__ - DEBUG - Metric 'transactions_processed' updated to 40 DEBUG:__main__:Metric 'transactions_processed' updated to 40 2026-06-10 11:09:17,808 - __main__ - INFO - Transaction TX-1781089757806146662 successful. INFO:__main__:Transaction TX-1781089757806146662 successful. 2026-06-10 11:09:17,824 - __main__ - ERROR - Transaction TX-1781089757824623092 failed. ERROR:__main__:Transaction TX-1781089757824623092 failed. 2026-06-10 11:09:17,838 - __main__ - DEBUG - Metric 'errors_logged' updated to 21 DEBUG:__main__:Metric 'errors_logged' updated to 21 2026-06-10 11:09:17,841 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089757824623092. Retrying in 0.71s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089757824623092. Retrying in 0.71s... 2026-06-10 11:09:18,568 - __main__ - DEBUG - Metric 'transactions_processed' updated to 41 DEBUG:__main__:Metric 'transactions_processed' updated to 41 2026-06-10 11:09:18,571 - __main__ - INFO - Transaction TX-1781089758567860390 successful. INFO:__main__:Transaction TX-1781089758567860390 successful. 2026-06-10 11:09:18,654 - __main__ - DEBUG - Metric 'transactions_processed' updated to 42 DEBUG:__main__:Metric 'transactions_processed' updated to 42 2026-06-10 11:09:18,656 - __main__ - INFO - Transaction TX-1781089758653852139 successful. INFO:__main__:Transaction TX-1781089758653852139 successful. 2026-06-10 11:09:18,745 - __main__ - ERROR - Transaction TX-1781089758745180832 failed. ERROR:__main__:Transaction TX-1781089758745180832 failed. 2026-06-10 11:09:18,756 - __main__ - DEBUG - Metric 'errors_logged' updated to 22 DEBUG:__main__:Metric 'errors_logged' updated to 22 2026-06-10 11:09:18,758 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089758745180832. Retrying in 0.89s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089758745180832. Retrying in 0.89s... 2026-06-10 11:09:19,658 - __main__ - ERROR - Transaction TX-1781089759658654815 failed. ERROR:__main__:Transaction TX-1781089759658654815 failed. 2026-06-10 11:09:19,669 - __main__ - DEBUG - Metric 'errors_logged' updated to 23 DEBUG:__main__:Metric 'errors_logged' updated to 23 2026-06-10 11:09:19,671 - __main__ - WARNING - Attempt 2/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089759658654815. Retrying in 1.28s... WARNING:__main__:Attempt 2/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089759658654815. Retrying in 1.28s... 2026-06-10 11:09:20,971 - __main__ - DEBUG - Metric 'transactions_processed' updated to 43 DEBUG:__main__:Metric 'transactions_processed' updated to 43 2026-06-10 11:09:20,974 - __main__ - INFO - Transaction TX-1781089760971804406 successful. INFO:__main__:Transaction TX-1781089760971804406 successful. 2026-06-10 11:09:21,004 - __main__ - DEBUG - Metric 'transactions_processed' updated to 44 DEBUG:__main__:Metric 'transactions_processed' updated to 44 2026-06-10 11:09:21,006 - __main__ - INFO - Transaction TX-1781089761004387173 successful. INFO:__main__:Transaction TX-1781089761004387173 successful. 2026-06-10 11:09:21,072 - __main__ - DEBUG - Metric 'transactions_processed' updated to 45 DEBUG:__main__:Metric 'transactions_processed' updated to 45 2026-06-10 11:09:21,074 - __main__ - INFO - Transaction TX-1781089761072497139 successful. INFO:__main__:Transaction TX-1781089761072497139 successful. 2026-06-10 11:09:21,163 - __main__ - ERROR - Transaction TX-1781089761162863839 failed. ERROR:__main__:Transaction TX-1781089761162863839 failed. 2026-06-10 11:09:21,175 - __main__ - DEBUG - Metric 'errors_logged' updated to 24 DEBUG:__main__:Metric 'errors_logged' updated to 24 2026-06-10 11:09:21,179 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089761162863839. Retrying in 0.61s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089761162863839. Retrying in 0.61s... 2026-06-10 11:09:21,807 - __main__ - ERROR - Transaction TX-1781089761807179907 failed. ERROR:__main__:Transaction TX-1781089761807179907 failed. 2026-06-10 11:09:21,819 - __main__ - DEBUG - Metric 'errors_logged' updated to 25 DEBUG:__main__:Metric 'errors_logged' updated to 25 2026-06-10 11:09:21,822 - __main__ - WARNING - Attempt 2/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089761807179907. Retrying in 1.47s... WARNING:__main__:Attempt 2/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089761807179907. Retrying in 1.47s... 2026-06-10 11:09:23,306 - __main__ - DEBUG - Metric 'transactions_processed' updated to 46 DEBUG:__main__:Metric 'transactions_processed' updated to 46 2026-06-10 11:09:23,309 - __main__ - INFO - Transaction TX-1781089763306072771 successful. INFO:__main__:Transaction TX-1781089763306072771 successful. 2026-06-10 11:09:23,361 - __main__ - ERROR - Transaction TX-1781089763361068074 failed. ERROR:__main__:Transaction TX-1781089763361068074 failed. 2026-06-10 11:09:23,372 - __main__ - DEBUG - Metric 'errors_logged' updated to 26 DEBUG:__main__:Metric 'errors_logged' updated to 26 2026-06-10 11:09:23,374 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089763361068074. Retrying in 0.95s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089763361068074. Retrying in 0.95s... 2026-06-10 11:09:24,339 - __main__ - DEBUG - Metric 'transactions_processed' updated to 47 DEBUG:__main__:Metric 'transactions_processed' updated to 47 2026-06-10 11:09:24,343 - __main__ - INFO - Transaction TX-1781089764339477430 successful. INFO:__main__:Transaction TX-1781089764339477430 successful. 2026-06-10 11:09:24,405 - __main__ - DEBUG - Metric 'transactions_processed' updated to 48 DEBUG:__main__:Metric 'transactions_processed' updated to 48 2026-06-10 11:09:24,407 - __main__ - INFO - Transaction TX-1781089764405479899 successful. INFO:__main__:Transaction TX-1781089764405479899 successful. 2026-06-10 11:09:24,462 - __main__ - DEBUG - Metric 'transactions_processed' updated to 49 DEBUG:__main__:Metric 'transactions_processed' updated to 49 2026-06-10 11:09:24,464 - __main__ - INFO - Transaction TX-1781089764462034249 successful. INFO:__main__:Transaction TX-1781089764462034249 successful. 2026-06-10 11:09:24,516 - __main__ - DEBUG - Metric 'transactions_processed' updated to 50 DEBUG:__main__:Metric 'transactions_processed' updated to 50 2026-06-10 11:09:24,519 - __main__ - INFO - Transaction TX-1781089764516659125 successful. INFO:__main__:Transaction TX-1781089764516659125 successful. 2026-06-10 11:09:24,586 - __main__ - DEBUG - Metric 'transactions_processed' updated to 51 DEBUG:__main__:Metric 'transactions_processed' updated to 51 2026-06-10 11:09:24,588 - __main__ - INFO - Transaction TX-1781089764586422747 successful. INFO:__main__:Transaction TX-1781089764586422747 successful. 2026-06-10 11:09:24,614 - __main__ - DEBUG - Metric 'transactions_processed' updated to 52 DEBUG:__main__:Metric 'transactions_processed' updated to 52 2026-06-10 11:09:24,617 - __main__ - INFO - Transaction TX-1781089764614807961 successful. INFO:__main__:Transaction TX-1781089764614807961 successful. 2026-06-10 11:09:24,646 - __main__ - DEBUG - Metric 'transactions_processed' updated to 53 DEBUG:__main__:Metric 'transactions_processed' updated to 53 2026-06-10 11:09:24,649 - __main__ - INFO - Transaction TX-1781089764646674343 successful. INFO:__main__:Transaction TX-1781089764646674343 successful. 2026-06-10 11:09:24,665 - __main__ - DEBUG - Metric 'transactions_processed' updated to 54 DEBUG:__main__:Metric 'transactions_processed' updated to 54 2026-06-10 11:09:24,668 - __main__ - INFO - Transaction TX-1781089764665153871 successful. INFO:__main__:Transaction TX-1781089764665153871 successful. 2026-06-10 11:09:24,725 - __main__ - DEBUG - Metric 'transactions_processed' updated to 55 DEBUG:__main__:Metric 'transactions_processed' updated to 55 2026-06-10 11:09:24,727 - __main__ - INFO - Transaction TX-1781089764725030188 successful. INFO:__main__:Transaction TX-1781089764725030188 successful. 2026-06-10 11:09:24,775 - __main__ - DEBUG - Metric 'transactions_processed' updated to 56 DEBUG:__main__:Metric 'transactions_processed' updated to 56 2026-06-10 11:09:24,777 - __main__ - INFO - Transaction TX-1781089764774993015 successful. INFO:__main__:Transaction TX-1781089764774993015 successful. 2026-06-10 11:09:24,859 - __main__ - DEBUG - Metric 'transactions_processed' updated to 57 DEBUG:__main__:Metric 'transactions_processed' updated to 57 2026-06-10 11:09:24,862 - __main__ - INFO - Transaction TX-1781089764859608937 successful. INFO:__main__:Transaction TX-1781089764859608937 successful. 2026-06-10 11:09:24,938 - __main__ - DEBUG - Metric 'transactions_processed' updated to 58 DEBUG:__main__:Metric 'transactions_processed' updated to 58 2026-06-10 11:09:24,940 - __main__ - INFO - Transaction TX-1781089764937904083 successful. INFO:__main__:Transaction TX-1781089764937904083 successful. 2026-06-10 11:09:25,006 - __main__ - ERROR - Transaction TX-1781089765006196128 failed. ERROR:__main__:Transaction TX-1781089765006196128 failed. 2026-06-10 11:09:25,017 - __main__ - DEBUG - Metric 'errors_logged' updated to 27 DEBUG:__main__:Metric 'errors_logged' updated to 27 2026-06-10 11:09:25,020 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089765006196128. Retrying in 0.64s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089765006196128. Retrying in 0.64s... 2026-06-10 11:09:25,672 - __main__ - DEBUG - Metric 'transactions_processed' updated to 59 DEBUG:__main__:Metric 'transactions_processed' updated to 59 2026-06-10 11:09:25,675 - __main__ - INFO - Transaction TX-1781089765672015347 successful. INFO:__main__:Transaction TX-1781089765672015347 successful. 2026-06-10 11:09:25,724 - __main__ - ERROR - Transaction TX-1781089765724283583 failed. ERROR:__main__:Transaction TX-1781089765724283583 failed. 2026-06-10 11:09:25,745 - __main__ - DEBUG - Metric 'errors_logged' updated to 28 DEBUG:__main__:Metric 'errors_logged' updated to 28 2026-06-10 11:09:25,752 - __main__ - WARNING - Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089765724283583. Retrying in 0.79s... WARNING:__main__:Attempt 1/3 failed for simulate_crypto_transaction: Failure in transaction TX-1781089765724283583. Retrying in 0.79s... 2026-06-10 11:09:26,567 - __main__ - DEBUG - Metric 'transactions_processed' updated to 60 DEBUG:__main__:Metric 'transactions_processed' updated to 60 2026-06-10 11:09:26,569 - __main__ - INFO - Transaction TX-1781089766567355864 successful. INFO:__main__:Transaction TX-1781089766567355864 successful. 2026-06-10 11:09:26,636 - __main__ - DEBUG - Metric 'transactions_processed' updated to 61 DEBUG:__main__:Metric 'transactions_processed' updated to 61 2026-06-10 11:09:26,638 - __main__ - INFO - Transaction TX-1781089766636034939 successful. INFO:__main__:Transaction TX-1781089766636034939 successful. 2026-06-10 11:09:26,692 - __main__ - INFO - Finished generating 50 synthetic transactions. INFO:__main__:Finished generating 50 synthetic transactions. 2026-06-10 11:09:26,695 - __main__ - INFO - --- Batch of synthetic transactions complete --- INFO:__main__:--- Batch of synthetic transactions complete ---
6. Summarize and Display Monitoring Data
Now, we'll summarize all the simulated activities and display the results using a Pandas DataFrame and print the aggregated metrics.
app_state['logger'].info("--- Summarizing and displaying monitoring data ---")
df_transactions, metrics_summary = summarize_monitoring_data(app_state)
print("\n--- Transaction History (last 5) ---")
display(df_transactions.tail())
print("\n--- Aggregated Metrics ---")
for metric, value in metrics_summary.items():
print(f"{metric.replace('_', ' ').title()}: {value}")
# Ensure Sentry events are sent before application exits
if SENTRY_DSN != "YOUR_SENTRY_DSN_HERE":
sentry_sdk.flush() # Flushes any buffered events to Sentry
app_state['logger'].info("Sentry events flushed.")
app_state['logger'].info("--- Monitoring data summary complete ---")2026-06-10 11:09:34,443 - __main__ - INFO - --- Summarizing and displaying monitoring data --- INFO:__main__:--- Summarizing and displaying monitoring data ---
--- Transaction History (last 5) ---
| id | amount | sender | receiver | timestamp | status | |
|---|---|---|---|---|---|---|
| 56 | TX-1781089764859608937 | 9.1150 | 0x472420496f5818b756b3dd7a66106bb4e806e0e9 | 0x3c969d493673f2e5528f057cc0b8679d48df0c38 | 2026-06-10 11:09:24.859685 | success |
| 57 | TX-1781089764937904083 | 2.6249 | 0x47fde583d7bc69ee1d7756f460d80b05263f57d1 | 0x473785720c167d96b346792e88cb7a0c794b4cfd | 2026-06-10 11:09:24.937978 | success |
| 58 | TX-1781089765672015347 | 8.6436 | 0xd15823617b8acd722d68c502bd8e74c5f4bc4731 | 0xba1e9fe8aa7e78f2b2e6e0d74540f1746bb81bd7 | 2026-06-10 11:09:25.672131 | success |
| 59 | TX-1781089766567355864 | 0.9541 | 0xb053bd94abf9b93dfd9a8859bab3c4563fa16964 | 0xb8fa8a1dc76931ef8c86e59e1f12813ce3e710a4 | 2026-06-10 11:09:26.567450 | success |
| 60 | TX-1781089766636034939 | 9.9564 | 0x1ed974b86d7aa0eded1791dcdf4322b8cf87847f | 0x8b256f9aedad9c54cde8a7a48bedeaea8d5ef3ef | 2026-06-10 11:09:26.636097 | success |
2026-06-10 11:09:34,472 - __main__ - INFO - Sentry events flushed. INFO:__main__:Sentry events flushed. 2026-06-10 11:09:34,475 - __main__ - INFO - --- Monitoring data summary complete --- INFO:__main__:--- Monitoring data summary complete ---
--- Aggregated Metrics --- Total Transactions: 61 Total Errors: 28 Network Failures: 0 Api Calls Failed: 0 Api Calls Success: 1 Successful Transactions: 61
7. Visualizations
Finally, we'll create some visualizations to better understand the transaction and error patterns.
app_state['logger'].info("--- Generating Visualizations ---")
if not df_transactions.empty:
# Plot 1: Transaction Status Distribution
plt.figure(figsize=(8, 5))
sns.countplot(x='status', data=df_transactions)
plt.title('Distribution of Transaction Statuses')
plt.xlabel('Transaction Status')
plt.ylabel('Number of Transactions')
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()
# Plot 2: Transaction Amounts over Time
df_transactions['time_elapsed'] = (df_transactions['timestamp'] - df_transactions['timestamp'].min()).dt.total_seconds()
plt.figure(figsize=(12, 6))
sns.lineplot(x='time_elapsed', y='amount', hue='status', data=df_transactions, marker='o', alpha=0.7)
plt.title('Simulated Crypto Transaction Amounts Over Time')
plt.xlabel('Time Elapsed (seconds)')
plt.ylabel('Amount')
plt.grid(True, linestyle='--', alpha=0.6)
plt.legend(title='Status')
plt.show()
# Plot 3: Error Type Distribution (if any)
# This requires processing the Sentry capture for actual error types or inferring from metrics
# For this demo, we'll visualize the metrics from the app_state
error_metrics = {k: v for k, v in metrics_summary.items() if 'error' in k and v > 0}
if error_metrics:
error_df = pd.DataFrame(list(error_metrics.items()), columns=['Error Type', 'Count'])
plt.figure(figsize=(10, 6))
sns.barplot(x='Count', y='Error Type', data=error_df.sort_values('Count', ascending=False))
plt.title('Distribution of Application Error Types')
plt.xlabel('Count')
plt.ylabel('Error Type')
plt.grid(axis='x', linestyle='--', alpha=0.7)
plt.show()
else:
app_state['logger'].info("No specific error metrics to visualize.")
else:
app_state['logger'].warning("No transactions to visualize.")
app_state['logger'].info("--- Visualizations complete ---")2026-06-10 11:09:39,003 - __main__ - INFO - --- Generating Visualizations --- INFO:__main__:--- Generating Visualizations ---
2026-06-10 11:09:39,587 - __main__ - INFO - --- Visualizations complete --- INFO:__main__:--- Visualizations complete ---
Production Considerations
When deploying Sentry for infrastructure monitoring in a production crypto environment, several best practices should be followed to ensure reliability, security, and performance. This table outlines key considerations.
| Aspect | Best Practices |
|---|---|
| Sentry DSN Management | Use environment variables (e.g., SENTRY_DSN) to store DSNs. Never hardcode DSNs directly into your application code. Ensure different DSNs for different environments (development, staging, production). |
| Sampling Rates | Adjust traces_sample_rate and profiles_sample_rate based on traffic and performance needs to manage data volume and Sentry quota usage. Start with lower rates (e.g., 0.1 for traces) in high-volume production systems. |
| Sensitive Data Scrubbing | Configure Sentry to automatically scrub sensitive information (e.g., private keys, seed phrases, sensitive user data, API keys) from events. Use in_app_include, in_app_exclude and before_send hooks to filter or modify event data. |
| Context Enrichment | Consistently add relevant context (user IDs, wallet addresses, transaction hashes, chain IDs, application version) to events using sentry_sdk.set_user(), sentry_sdk.set_context(), and sentry_sdk.set_tag(). This is crucial for debugging crypto-specific issues. |
| Integrations | Integrate Sentry with your existing alert systems (e.g., PagerDuty, Slack, Opsgenie) and incident management workflows. Integrate with logging frameworks (e.g., logging module as shown) to capture log messages as breadcrumbs or events. |
| Performance Monitoring | Leverage Sentry's performance monitoring (traces_sample_rate > 0) to track transaction durations, identify bottlenecks in critical crypto operations (e.g., token transfers, smart contract interactions, API calls to exchanges). |
| Error Prioritization | Define clear alert rules in Sentry to prioritize critical errors (e.g., failed transactions, security exceptions) and route them to the appropriate teams or individuals for immediate attention. |
| Rate Limiting | Monitor Sentry's own outbound rate limits to avoid dropped events. Configure client-side rate limiting in the SDK (max_breadcrumbs, max_value_length) or server-side inbound filters in Sentry to manage event volume. |
| Offline Buffering | For applications that might operate in unstable network environments, consider using Sentry SDKs that offer offline caching mechanisms to ensure events are eventually delivered when connectivity is restored. |
| Regular Review | Regularly review Sentry dashboards and issue streams to identify recurring problems, understand error trends, and ensure that your monitoring setup is effectively capturing the necessary information. |
Conclusion
This notebook provided a comprehensive guide to integrating Sentry for robust error tracking in crypto applications. We've covered:
- Initialization: Setting up the Sentry SDK and application state.
- Core Functionality: Implementing functions for simulating crypto transactions, handling external API calls with exponential backoff retries, and updating metrics.
- Error Handling: Demonstrating how Sentry automatically captures exceptions and how custom events can be logged.
- Contextual Data: Enriching error reports with breadcrumbs, tags, and extra data for easier debugging.
- Metrics & Visualization: Collecting operational metrics and visualizing transaction outcomes and error distributions.
By leveraging tools like Sentry, developers can significantly enhance the reliability and stability of their crypto applications, ensuring quick identification and resolution of critical issues in a complex and high-stakes environment.
@_exponential_backoff_retry(max_retries=4, base_delay=1.0, exceptions_to_catch=(ConnectionError, TimeoutError, ValueError))
def call_external_api(state: dict, endpoint: str, params: dict, fail_chance: float = 0.3) -> dict:
"""
Simulates an external API call for crypto data.
"""
logger = state['logger']
sentry_sdk.add_breadcrumb(
category='api_call',
message=f'Calling endpoint: {endpoint}',
level='info',
data={'endpoint': endpoint, 'params': params}
)
if random.random() < fail_chance:
logger.error(f"API call to {endpoint} failed.")
state = update_metrics(state, 'api_errors')
raise ConnectionError(f"API {endpoint} is unreachable.")
logger.info(f"API call to {endpoint} successful.")
state = update_metrics(state, 'api_success')
return state