### Install and Configure pre-commit Source: https://github.com/elastic/apm-agent-python/blob/main/CONTRIBUTING.md Install pre-commit to automatically format code and ensure style consistency. Run 'pre-commit install' to set up the git hooks. ```bash pip install pre-commit # or "brew install pre-commit" if you use Homebrew ``` ```bash pre-commit install ``` -------------------------------- ### Install OpenTelemetry Libraries Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/opentelemetry-api-bridge.md Install the necessary OpenTelemetry libraries for the Elastic APM agent. Use the `[opentelemetry]` extra if installing `elastic-apm` for the first time, or install `opentelemetry-api` and `opentelemetry-sdk` separately if `elastic-apm` is already installed. ```bash pip install elastic-apm[opentelemetry] ``` ```bash pip install opentelemetry-api opentelemetry-sdk ``` -------------------------------- ### Install Elastic APM Agent Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/asgi-middleware.md Install the Elastic APM agent using pip. Alternatively, add 'elastic-apm' to your project's requirements.txt file. ```bash pip install elastic-apm ``` -------------------------------- ### Install Elastic APM Agent for Flask Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/flask-support.md Install the agent using pip. Ensure you use version 2.0 or higher for apm-server 6.2+. ```bash pip install "elastic-apm[flask]" ``` -------------------------------- ### Check elasticapm-run Version Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/wrapper-support.md Verify the installed version of the `elasticapm-run` script. ```bash $ elasticapm-run --version elasticapm-run 6.14.0 ``` -------------------------------- ### Create a Span using Tracer Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/opentelemetry-api-bridge.md Instantiate the `Tracer` and use it to start a span as the current span. This is useful for custom instrumentation within your application. ```python from elasticapm.contrib.opentelemetry import Tracer tracer = Tracer(__name__) with tracer.start_as_current_span("test"): # Do some work ``` -------------------------------- ### Run Flask Application with elasticapm-run Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/wrapper-support.md Use `elasticapm-run` to start a Flask development server. This allows for instrumentation without code changes. ```bash $ elasticapm-run flask run ``` -------------------------------- ### Start Integration Testing Environment Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/run-tests-locally.md Spin up a local integration testing environment using Docker Compose, including a specific Elastic Stack version, the APM Python agent from a local checkout, and the Opbeans Python application. ```bash $ ./scripts/compose.py start 7.3 \ --with-agent-python-django --with-opbeans-python \ --opbeans-python-agent-local-repo=~/elastic/apm-agent-python ``` -------------------------------- ### Install Elastic APM Agent Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/aiohttp-server-support.md Install the Elastic APM agent using pip. This command can also be added to your project's requirements.txt file. ```bash $ pip install elastic-apm ``` -------------------------------- ### Create a Span using get_tracer Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/opentelemetry-api-bridge.md Alternatively, obtain a tracer instance using `get_tracer` and then start a span as the current span. This method also supports custom instrumentation. ```python from elasticapm.contrib.opentelemetry import trace tracer = trace.get_tracer(__name__) with tracer.start_as_current_span("test"): # Do some work ``` -------------------------------- ### Get Client Singleton Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/api-reference.md Retrieves the Client singleton instance. This is particularly useful for framework integrations where the client is automatically instantiated. ```APIDOC ## `elasticapm.get_client()` Retrieves the `Client` singleton. This is useful for many framework integrations, where the client is instantiated automatically. ```python client = elasticapm.get_client() client.capture_message('foo') ``` ``` -------------------------------- ### Begin Transaction Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/api-reference.md Begins tracking a transaction, typically called at the start of a request or background task. Supports optional trace parent linking. ```APIDOC ## `Client.begin_transaction()` Begin tracking a transaction. Should be called e.g. at the beginning of a request or when starting a background task. Example: ```python client.begin_transaction('processors') ``` * `transaction_type`: (**required**) A string describing the type of the transaction, e.g. `'request'` or `'celery'`. * `trace_parent`: (**optional**) A `TraceParent` object. See [TraceParent generation](#traceparent-api). * `links`: (**optional**) A list of `TraceParent` objects to which this transaction is causally linked. ``` -------------------------------- ### Begin APM Transaction Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/api-reference.md Start tracking a transaction by calling client.begin_transaction() with a transaction type. This should be called at the beginning of a request or background task. ```python client.begin_transaction('processors') ``` -------------------------------- ### Run Local Unit Tests Source: https://github.com/elastic/apm-agent-python/blob/main/CONTRIBUTING.md Install requirements and run 'make test' to execute local unit tests. Pytest will discover and run tests, skipping those with unmet dependencies. ```bash pip install -r tests/requirements/reqs-flask-1.1.txt ``` ```bash make test ``` -------------------------------- ### Check Django APM Configuration Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/django-support.md Use the `elasticapm check` Django management command to verify your Elastic APM setup. ```bash python manage.py elasticapm check ``` -------------------------------- ### Initialize ElasticAPM with Flask App (Environment Variables) Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/flask-support.md Initialize the ElasticAPM agent for your Flask application using environment variables. This is a common setup method. ```python from elasticapm.contrib.flask import ElasticAPM app = Flask(__name__) apm = ElasticAPM(app) ``` -------------------------------- ### Configure APM via AWS Web Console Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/lambda-support.md Add these environment variables to your Lambda function configuration in the AWS Management Console for basic APM setup. The send strategy 'background' is recommended for production environments with steady load. ```bash AWS_LAMBDA_EXEC_WRAPPER = /opt/python/bin/elasticapm-lambda <1> ELASTIC_APM_LAMBDA_APM_SERVER = <2> ELASTIC_APM_SECRET_TOKEN = <3> ELASTIC_APM_SEND_STRATEGY = background <4> ``` -------------------------------- ### Create TraceParent from String Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/api-reference.md Create a `TraceParent` object from its string representation. This is useful for starting a transaction that is a child of a parent trace, essential for distributed tracing. ```python parent = elasticapm.trace_parent_from_string('00-03d67dcdd62b7c0f7a675424347eee3a-5f0e87be26015733-01') client.begin_transaction('processors', trace_parent=parent) ``` -------------------------------- ### Run flake8 Linter Locally Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/run-tests-locally.md Trigger the flake8 code linter locally using pre-commit. This checks for style guide violations and potential errors. ```bash $ pre-commit run -a flake8 ``` -------------------------------- ### Ignore specific views using TRANSACTIONS_IGNORE_PATTERNS Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/django-support.md Configure regular expressions to exclude specific transactions from being reported. This example ignores OPTIONS requests and views in 'views.api.v2'. ```python ELASTIC_APM['TRANSACTIONS_IGNORE_PATTERNS'] = ['^OPTIONS ', 'views.api.v2'] ``` -------------------------------- ### Manually Instrumenting a Transaction Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/instrumenting-custom-code.md Use this to manually start and end transactions for custom code blocks. Ensure you have initialized the APM client and can extract trace parent information from incoming headers if needed. ```python parent = elasticapm.trace_parent_from_headers(headers_dict) client.begin_transaction(transaction_type="script", trace_parent=parent) # Do some work client.end_transaction(name=__name__, result="success") ``` -------------------------------- ### Create a Custom Processor to Remove Stacktrace Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/sanitizing-data.md Define a custom processor function decorated with `@for_events` to target specific event types. This example removes the 'stacktrace' from 'exception' fields in ERROR events. ```python from elasticapm.conf.constants import ERROR from elasticapm.processors import for_events @for_events(ERROR) def my_processor(client, event): if 'exception' in event and 'stacktrace' in event['exception']: event['exception'].pop('stacktrace') return event ``` -------------------------------- ### Client Instantiation Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/api-reference.md Import and instantiate the Client class to create a client instance. Framework integrations often handle this automatically. ```APIDOC ## Client Instantiation To create a `Client` instance, import it and call its constructor: ```python from elasticapm import Client client = Client({'SERVICE_NAME': 'example'}, **defaults) ``` * `config`: A dictionary, with key/value configuration. For the possible configuration keys, see [Configuration](/reference/configuration.md). * `**defaults`: default values for configuration. These can be omitted in most cases, and take the least precedence. ``` -------------------------------- ### Initialize Elastic APM with Initialization Arguments Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/starlette-support.md Configure the agent using initialization arguments by creating an APM client and passing it to the ElasticAPM middleware. ```python from starlette.applications import Starlette from elasticapm.contrib.starlette import make_apm_client, ElasticAPM apm = make_apm_client({ 'SERVICE_NAME': '', 'SECRET_TOKEN': '', 'SERVER_URL': '', }) app = Starlette() app.add_middleware(ElasticAPM, client=apm) ``` -------------------------------- ### Instantiate Elastic APM Client Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/api-reference.md Import and instantiate the Client class to create an APM client instance. Configuration is provided via a dictionary. Framework integrations often handle this automatically. ```python from elasticapm import Client client = Client({'SERVICE_NAME': 'example'}, **defaults) ``` -------------------------------- ### Import Optional Dependencies with pytest.importorskip Source: https://github.com/elastic/apm-agent-python/blob/main/CONTRIBUTING.md Conditionally import dependencies required only for specific tests. This prevents errors if the dependency is not installed. ```python foodriver = pytest.importorskip("foodriver") ``` -------------------------------- ### Configure File Handler with Custom Formatter Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/logs.md Use this to set up a file handler with a custom log formatter. ```python import logging fh = logging.FileHandler('spam.log') formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") fh.setFormatter(formatter) ``` -------------------------------- ### Get Current Span ID Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/api-reference.md Retrieves the identifier for the current span. Requires APM agent version 5.2.0 or later. ```python import elasticapm span_id = elasticapm.get_span_id() ``` -------------------------------- ### Test Documentation Generation Locally Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/run-tests-locally.md Execute the script to test if documentation can be generated without errors locally. ```bash $ ./tests/scripts/docker/docs.sh ``` -------------------------------- ### Get Current Transaction ID Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/api-reference.md Retrieves the unique identifier for the current transaction. Requires APM agent version 5.2.0 or later. ```python import elasticapm transaction_id = elasticapm.get_transaction_id() ``` -------------------------------- ### Pass Configuration Options as Arguments Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/wrapper-support.md Provide configuration settings directly to `elasticapm-run` using the `--config` argument, overriding environment variables if necessary. ```bash $ elasticapm-run --config "service_name=my_flask_app" --config "debug=true" flask run ``` -------------------------------- ### Get Current Trace ID Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/api-reference.md Retrieves the trace ID associated with the current transaction. Requires APM agent version 5.2.0 or later. ```python import elasticapm trace_id = elasticapm.get_trace_id() ``` -------------------------------- ### Initialize ElasticAPM on the Fly with init_app Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/flask-support.md Use the init_app hook to add the application to the agent on the fly, suitable for applications built dynamically. ```python from elasticapm.contrib.flask import ElasticAPM apm = ElasticAPM() def create_app(): app = Flask(__name__) apm.init_app(app, service_name='', secret_token='') return app ``` -------------------------------- ### Run Test Suite with Specific Python and Framework Versions Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/run-tests-locally.md Execute the test suite locally using Docker for a specific combination of Python and framework versions. The `` argument specifies a directory for pip cache. ```bash $ ./tests/scripts/docker/run_tests.sh python-version framework-version ``` -------------------------------- ### Initialize ElasticAPM with Initialization Arguments Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/flask-support.md Initialize the agent directly with service name and secret token as arguments. This is useful for simpler configurations. ```python from elasticapm.contrib.flask import ElasticAPM apm = ElasticAPM(app, service_name='', secret_token='') ``` -------------------------------- ### Get Elastic APM Client Singleton Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/api-reference.md Retrieve the singleton Client instance using elasticapm.get_client(). This is useful for framework integrations where the client is automatically instantiated. ```python client = elasticapm.get_client() client.capture_message('foo') ``` -------------------------------- ### Initialize Elastic APM with Environment Variables Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/aiohttp-server-support.md Initialize the Elastic APM agent for an aiohttp application using environment variables for configuration. Ensure the agent is imported and instantiated with the aiohttp application object. ```python from aiohttp import web from elasticapm.contrib.aiohttp import ElasticAPM app = web.Application() apm = ElasticAPM(app) ``` -------------------------------- ### Register and Use Base MetricSet Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/metrics.md Use this when you need to manually collect and send custom metrics. Ensure the `elasticapm` library is imported. ```python from elasticapm.metrics.base_metrics import MetricSet client = elasticapm.Client() metricset = client.metrics.register(MetricSet) for x in range(10): metricset.counter("my_counter").inc() ``` -------------------------------- ### Configure Metrics Sets Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/configuration.md Define the list of MetricSet import paths to be used for collecting metrics. This allows for custom metric collection. ```python ["elasticapm.metrics.sets.cpu.CPUMetricSet"] ``` -------------------------------- ### Get Current Trace Parent Header Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/api-reference.md Retrieve the string representation of the current transaction's `TraceParent` object. This is useful for propagating trace context to downstream services. ```python elasticapm.get_trace_parent_header() ``` -------------------------------- ### Initialize Elastic APM with Application Settings Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/aiohttp-server-support.md Configure the Elastic APM agent by defining settings within the application's settings dictionary under the 'ELASTIC_APM' key. This method allows for direct configuration of service name and secret token. ```python from aiohttp import web from elasticapm.contrib.aiohttp import ElasticAPM app = web.Application() app['ELASTIC_APM'] = { 'SERVICE_NAME': '', 'SECRET_TOKEN': '', } pm = ElasticAPM(app) ``` -------------------------------- ### Define Docker Dependencies and Connection URLs Source: https://github.com/elastic/apm-agent-python/blob/main/CONTRIBUTING.md Specify Docker dependencies and connection URLs in the environment script for services required by the instrumentation tests. ```bash DOCKER_DEPS="foo" FOO_CONNECTION_URL="http://foo:4711" ``` -------------------------------- ### Capture Exception using get_client() Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/flask-support.md Capture an exception using the global client obtained via get_client(). This is an alternative to using the apm instance directly. ```python from elasticapm import get_client @app.route('/') def bar(): try: 1 / 0 except ZeroDivisionError: get_client().capture_exception() ``` -------------------------------- ### Integrate Flask with RUM Agent Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/flask-support.md Correlate browser performance measurements with backend Flask app measurements by providing RUM agent with backend Trace ID and Span ID. The context processor is automatically installed on ElasticAPM initialization. Update your RUM agent initialization call with the provided template variables. ```javascript elasticApm.init({ serviceName: "my-frontend-service", pageLoadTraceId: "{{ apm["trace_id"] }}", pageLoadSpanId: "{{ apm["span_id"]() }}", pageLoadSampled: {{ apm["is_sampled_js"] }} }) ``` -------------------------------- ### Automatically Instrument Libraries Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/api-reference.md Call this function early in your application's startup to automatically instrument various standard and third-party libraries. For supported frameworks, this is often handled automatically. ```python import elasticapm elasticapm.instrument() ``` -------------------------------- ### Initialize APM Agent with Environment Variables Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/sanic-support.md Initialize the Elastic APM agent for your Sanic application using environment variables for configuration. ```python from sanic import Sanic from elasticapm.contrib.sanic import ElasticAPM app = Sanic(name="elastic-apm-sample") apm = ElasticAPM(app=app) ``` -------------------------------- ### Run Custom Python Script with elasticapm-run Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/wrapper-support.md Execute any Python script using `elasticapm-run` for integrated APM instrumentation. ```bash $ elasticapm-run python myapp.py ``` -------------------------------- ### Check elasticapm-run Version via Module Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/wrapper-support.md Alternatively, check the version by running the wrapper module directly using Python. ```bash $ python -m elasticapm.instrumentation.wrapper --version elasticapm-run 6.14.0 ``` -------------------------------- ### Run isort Linter Locally Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/run-tests-locally.md Trigger the isort code linter locally using pre-commit. This helps ensure consistent import sorting. ```bash $ pre-commit run -a isort ``` -------------------------------- ### Configure Custom Metric Sets via Environment Variable Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/metrics.md Configure custom metric sets by providing a comma-separated list of import strings to the `ELASTIC_APM_METRICS_SETS` environment variable. This allows you to specify multiple custom metric sets, including built-in ones like CPU metrics and your own custom implementations. ```bash ELASTIC_APM_METRICS_SETS="elasticapm.metrics.sets.cpu.CPUMetricSet,myapp.metrics.MyMetricSet" ``` -------------------------------- ### Add Instrumentation to Matrix Build Configuration Source: https://github.com/elastic/apm-agent-python/blob/main/CONTRIBUTING.md Include new instrumentations in the matrix build configuration files for pull requests and nightly builds. ```yaml - foo-newest ``` -------------------------------- ### Add APM Layers in Serverless Framework Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/lambda-support.md Configure your `serverless.yml` file by adding the ARNs for the APM extension and agent layers to the `layers` property of your function definition. Replace region and architecture placeholders as needed. ```yaml ... functions: yourLambdaFunction: handler: ... layers: - arn:aws:lambda:{AWS_REGION}:267093732750:layer:elastic-apm-extension-{{apm-lambda-ext-v}}-{ARCHITECTURE}:1 - arn:aws:lambda:{AWS_REGION}:267093732750:layer:elastic-apm-python-{{apm-python-v}}:{{apm-python-layer-v}} ... ``` -------------------------------- ### Initialize Elastic APM with Environment Variables Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/tornado-support.md Initialize the Elastic APM agent for your Tornado application using environment variables. Ensure the agent is imported and instantiated with the Tornado application. ```python import tornado.web from elasticapm.contrib.tornado import ElasticAPM app = tornado.web.Application() apm = ElasticAPM(app) ``` -------------------------------- ### Define Requirements for Instrumented Package Source: https://github.com/elastic/apm-agent-python/blob/main/CONTRIBUTING.md Create requirement files to specify dependencies for testing specific versions of an instrumented package. Includes base requirements. ```text foodriver -r reqs-base.txt ``` -------------------------------- ### Initialize Elastic APM with Application Settings Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/tornado-support.md Configure the Elastic APM agent using the ELASTIC_APM dictionary in your Tornado application's settings. This method allows for direct configuration of service name and secret token. ```python import tornado.web from elasticapm.contrib.tornado import ElasticAPM app = tornado.web.Application() app.settings['ELASTIC_APM'] = { 'SERVICE_NAME': '', 'SECRET_TOKEN': '', } apm = ElasticAPM(app) ``` -------------------------------- ### Wrap ASGI App with ASGITracingMiddleware Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/asgi-middleware.md Wrap your ASGI application with ASGITracingMiddleware to enable Elastic APM tracing. Ensure you set an appropriate transaction name in your routes using elasticapm.set_transaction_name(). ```python from elasticapm.contrib.asgi import ASGITracingMiddleware app = MyGenericASGIApp() # depending on framework app = ASGITracingMiddleware(app) ``` -------------------------------- ### Configure APM in serverless.yml Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/lambda-support.md Set APM environment variables in your Serverless Framework service configuration. The 'background' send strategy is recommended for production to balance performance and data transmission. ```yaml ... functions: yourLambdaFunction: ... environment: AWS_LAMBDA_EXEC_WRAPPER: /opt/python/bin/elasticapm-lambda ELASTIC_APM_LAMBDA_APM_SERVER: ELASTIC_APM_SECRET_TOKEN: ELASTIC_APM_SEND_STRATEGY: background <1> ... ``` -------------------------------- ### Create a Custom MetricSet Class Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/metrics.md Create a custom `MetricSet` by inheriting from the base class and overriding the `before_collect` method. This method is called before metrics are collected and sent, allowing you to gather and set custom metric values. Ensure `myapp.some_value` is accessible when this method is invoked. ```python from elasticapm.metrics.base_metrics import MetricSet class MyAwesomeMetricSet(MetricSet): def before_collect(self): self.gauge("my_gauge").set(myapp.some_value) ``` -------------------------------- ### Initialize Elastic APM with Environment Variables Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/starlette-support.md Add the ElasticAPM middleware to your Starlette application to initialize the agent using environment variables. Ensure this middleware is added last if using repeated add_middleware calls, or first if providing a list of middleware, to avoid contextvar propagation issues. ```python from starlette.applications import Starlette from elasticapm.contrib.starlette import ElasticAPM app = Starlette() app.add_middleware(ElasticAPM) ``` -------------------------------- ### Configure Flask Service Name and Secret Token Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/configuration.md Set the service name and secret token for Flask applications using `app.config`. ```python app.config['ELASTIC_APM'] = { 'SERVICE_NAME': 'my-app', 'SECRET_TOKEN': 'changeme', } apm = ElasticAPM(app) ``` -------------------------------- ### Configure Django Service Name and Secret Token Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/configuration.md Set the service name and secret token for Django applications in `settings.py`. ```python ELASTIC_APM = { 'SERVICE_NAME': 'my-app', 'SECRET_TOKEN': 'changeme', } ``` -------------------------------- ### Initialize RUM Agent with Trace and Span IDs Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/django-support.md Update the RUM agent initialization in your base template to include `pageLoadTraceId`, `pageLoadSpanId`, and `pageLoadSampled` from the APM context. ```javascript elasticApm.init({ serviceName: "my-frontend-service", pageLoadTraceId: "{{ apm.trace_id }}", pageLoadSpanId: "{{ apm.span_id }}", pageLoadSampled: {{ apm.is_sampled_js }} }) ``` -------------------------------- ### Run Black Formatter Locally Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/run-tests-locally.md Trigger the Black code formatter locally using pre-commit. This ensures code adheres to the Black formatting standard. ```bash $ pre-commit run -a black ``` -------------------------------- ### Configure APM Agent with External Configuration File Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/sanic-support.md Configure the APM agent by referencing an external Python file containing settings prefixed with ELASTIC_APM_. ```python # Create a file named external_config.py in your application # If you want this module based configuration to be used for APM, prefix them with ELASTIC_APM_ ELASTIC_APM_SERVER_URL = "https://serverurl.example.com:443" ELASTIC_APM_SECRET_TOKEN = "sometoken" ``` ```python from sanic import Sanic from elasticapm.contrib.sanic import ElasticAPM app = Sanic(name="elastic-apm-sample") app.config.update_config("path/to/external_config.py") apm = ElasticAPM(app=app) ``` -------------------------------- ### Configure File Handler with Elastic APM Formatter Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/logs.md Replace the default Formatter with the Elastic APM Formatter to automatically include APM identifiers in log messages. ```python import logging from elasticapm.handlers.logging import Formatter fh = logging.FileHandler('spam.log') formatter = Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") fh.setFormatter(formatter) ``` -------------------------------- ### Add elasticapm.contrib.django to INSTALLED_APPS Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/django-support.md Include the Django contrib app in your project's INSTALLED_APPS setting to enable APM integration. ```python INSTALLED_APPS = ( # ... 'elasticapm.contrib.django', ) ``` -------------------------------- ### Add RUM Tracing Context Processor to Django TEMPLATES Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/django-support.md Configure Django's TEMPLATES setting to include the `rum_tracing` context processor for correlating browser and backend performance measurements. ```python TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'context_processors': [ # ... 'elasticapm.contrib.django.context_processors.rum_tracing', ], }, }, ] ``` -------------------------------- ### Set Service Name via Environment Variable Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/configuration.md Configure the service name using an environment variable when running a Python application. ```bash ELASTIC_APM_SERVICE_NAME=foo python manage.py runserver ``` -------------------------------- ### TraceParent.from_string() Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/api-reference.md Creates a `TraceParent` object from its string representation. This is useful for initiating transactions that are children of an existing trace, essential for distributed tracing. ```APIDOC ## `elasticapm.trace_parent_from_string()` ### Description Creates a `TraceParent` object from its string representation. This is useful for initiating transactions that are children of an existing trace, essential for distributed tracing. ### Parameters * `traceparent_string` (required, string): A string representation of a `TraceParent` object. ### Example ```python parent = elasticapm.trace_parent_from_string('00-03d67dcdd62b7c0f7a675424347eee3a-5f0e87be26015733-01') client.begin_transaction('processors', trace_parent=parent) ``` ``` -------------------------------- ### Set Service Name via Inline Configuration Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/configuration.md Configure the service name directly in Python code when initializing the APM client. ```python apm_client = Client(service_name="foo") ``` -------------------------------- ### Set Service Name via Django Settings Source: https://github.com/elastic/apm-agent-python/blob/main/docs/reference/configuration.md Configure the service name for Django applications within the `settings.py` file. ```python ELASTIC_APM = { "SERVICE_NAME": "foo", } ```