Python transaction API

The Python agent transaction API provides calls that affect the currently executing transaction. Except for record_exception and record_custom_event, you must call these functions inside an instrumented transaction.

The API call format is newrelic.agent. followed by the API name and values; for example, newrelic.agent.current_transaction(). For your convenience, the headings below show the API name, followed by the complete API call format and additional details.

Return the current transaction

Some Python agent API calls require you to pass in an object for the current transaction. To retrieve this object, use the current_transaction call:

newrelic.agent.current_transaction()

Returns a transaction object corresponding to the current web transaction or background task being monitored. Will return None where there is no active transaction.

The transaction object itself does not present any public API, but may be required to be passed in certain circumstances to other API calls when implementing custom instrumentation.

Configure transaction instrumentation

Use the following calls to set transaction names and configure transaction instrumentation. This API call should be used inside the function that creates a transaction:

newrelic.agent.set_transaction_name(name, group=None, priority=None)

Sets the name of the current transaction.

name = '%s/%s' % (controller, function) 
group = 'Python/WebFramework/Controller'

newrelic.agent.set_transaction_name(name, group)

The group can be used to categorize what the name represents. If not supplied, the group will default to Function in expectation that the name is of the form module:class.function or module:function and represents the name of the function being executed. It is recommended that any custom group be prefixed with Python/ when using the Python agent unless guidance otherwise is given.

If the priority is left as the default value of None, the new name will always override any existing value. If the priority is defined as a numeric value, the name will override an existing name only if the specified priority is greater than or equal to the existing priority.

The priority can generally be ignored unless implementing custom instrumentation for a web framework where there may be successive points where you may wish to set the name, such as middleware, view handlers or error handlers and you do not necessarily wish to give priority to the very last to execute.

newrelic.agent.set_background_task(flag=True)

Allows a transaction to be explicitly marked as a background task.

A monitored transaction will either be classified as a web transaction or a background task at the start of the transaction, based on which type of entry point wrapper initiated monitoring. In the case of a web transaction, if it is a long running transaction triggered by an external job to perform maintenance, it may result in response time averages and Apdex metrics being skewed. In this case you may wish to reclassify the web transaction as being a background task.

In the case of a web transaction it can also be flagged to be recorded as a background task by setting the newrelic.set_background_task key for the specific request in the WSGI environ dictionary passed by the WSGI server into the WSGI application being monitored.

newrelic.agent.end_of_transaction()

The transaction will be marked immediately as having been completed with the response time reported only being up to this point. No additional performance breakdown metrics will be collected for the remainder of the transaction, although the details of any Python exceptions which occur will still be recorded and reported.

This might be used where a large response is being streamed back for the web transaction, only the initial part of the transaction is of interest, and you don't want to flag the transaction as a background task to avoid skewing of response time averages and Apdex metrics.

newrelic.agent.ignore_transaction(flag=True) 

Allows a transaction to be completely ignored, with no details of the transaction being reported.

In the case of a web transaction it can also be flagged to be ignored by setting the newrelic.ignore_transaction key for the specific request in the WSGI environ dictionary passed by the WSGI server into the WSGI application being monitored.

newrelic.agent.suppress_transaction_trace(flag=True) 

Indicates that the current transaction should not be a candidate for capture as a sample transaction trace.

In the case of a web transaction it can also be flagged to be ignored by setting the newrelic.suppress_transaction_trace key for the specific request in the WSGI environ dictionary passed by the WSGI server into the WSGI application being monitored.

This exists so that a recurring long running transaction could be ignored for the purposes of slow transaction monitoring. The need for this call has largely been superseded due to a better algorithm for sample slow transaction selection which gives a lower weighting to transactions where a prior trace has recently been collected.

newrelic.agent.suppress_apdex_metric(flag=True) 

Suppress the generation of the Apdex metric for a web transaction.

Generation of the Apdex metric can also be flagged to be suppressed by setting the newrelic.suppress_apdex_metric key for the specific request in the WSGI environ dictionary passed by the WSGI server into the WSGI application being monitored.

Record exceptions and custom events

Unlike other transaction API calls, these methods can also be used outside of a transaction, making it possible to record an exception or custom event before a transaction begins, or after one ends.

Use these calls to record an error, or to report a custom event to New Relic Insights:

newrelic.agent.record_exception(exc=None, value=None, tb=None, *, params={}, ignore_errors=[], application=None) 

Records the details of the Python exception against the transaction as an error for display in the UI. You can record up to five distinct exceptions per transaction, and up to 20 total exceptions across all transactions per harvest cycle.

import sys

try: 
    ... 
except: 
    newrelic.agent.record_exception(*sys.exc_info()) 
    raise 

If no exception details are provided, the details of the exception currently being handled will be used.

Additional custom parameters to be displayed along with custom parameters already recorded for the transaction can be provided as a dictionary via the params keyword argument.

If certain types of exceptions should always be ignored and never recorded, a list of the exception type names in the form module:class which are to be ignored can be passed via the ignore_errors keyword argument.

If it is necessary to filter exceptions dynamically based on the attributes of a specific exception type, a callback function can instead be supplied.

def _ignore_errors(exc, value, tb): 
    if instance(value, HTTPError): 
        if value.status == 404: 
            return True

newrelic.agent.record_exception(ignore_errors=_ignore_errors) 

The return value for the callable if the exception is to be ignored should be True. False should be returned if the exception should never be ignored regardless of any other checks, and None if subsequent checks and inbuilt rules should determine if the exception should be ignored. A callback would normally return either True or None.

When record_exception() is called within the context of a monitored web request or background task, the details of the exception will be reported against the application that the request or task is being reported to.

If called outside of the context of a monitored web request or background task, the call will be ignored unless the application keyword argument is provided and an application object corresponding to the application against which the exception should be recorded is provided. A suitable application object can be obtained using the newrelic.agent.application() function.

newrelic.agent.record_custom_event(event_type, params, application=None)

Record a custom event that can be viewed and queried in Insights.

The event_type defines the name (or type) of the custom event, and must be a string. Attributes of the custom event should be passed in as a dictionary via the params keyword argument. Only attributes passed in as params are added. No additional attributes recorded for the transaction are added to custom events.

For limits and restrictions on event_type and params, see Limits and restricted characters and Reserved words.

If called outside of the context of a monitored web request or background task, the call will be ignored unless the application keyword argument is provided and an application object corresponding to the application against which the exception should be recorded is provided. A suitable application object can be obtained using the newrelic.agent.application() function.

Capture attributes and parameters

Use these calls to capture Python agent attributes:

newrelic.agent.add_custom_parameter(key, value) 

Records the key/value pair against the transaction for display in the UI in the case of an error being recorded for the transaction, or if a transaction trace was captured for the transaction. The key must be a string. The value must be either a string, integer, float or boolean.

Before creating custom attributes, review New Relic's list of reserved terms used by NRQL and Insights. Otherwise unexpected results may occur.

This method is deprecated, and aliased to add_custom_parameter(). Use add_custom_parameter() instead.

newrelic.agent.add_user_attribute(key, value) 

Records the key/value pair against user attributes to be associated with real user monitoring browser traces and displayed in the UI. Current allowed values for the key are:

  • user
  • account
  • product
newrelic.agent.capture_request_params(flag=True) 

Force the capture of any web transaction query string parameters, ignoring any setting in the agent configuration.

The capture of the query string parameters can also be flagged by setting the newrelic.capture_request_params key for the specific request in the WSGI environ dictionary passed by the WSGI server into the WSGI application being monitored.

If the agent is operating in high security mode, it is not possible to enable the capture of query string parameters. Calling this API, or setting the WSGI environment variable, will have no effect.

Control New Relic Browser

Use these methods to return the JavaScript header or footer, or to disable the New Relic Browser header on particular pages:

newrelic.agent.disable_browser_autorum(flag=True) 

Disables any automatic mechanism provided for a specific web framework for inserting the JavaScript header/footer for real user monitoring into HTML pages. This only affects the current web request and must be called prior to the point where the header/footer are being inserted by the framework.

Disabling can also be flagged by setting the newrelic.disable_browser_autorum key for the specific request in the WSGI environ dictionary passed by the WSGI server into the WSGI application being monitored.

newrelic.agent.get_browser_timing_header() 

Returns the JavaScript header to be included in HTML pages for page load timing. Useful for inserting the header manually, rather than relying on the automatic insertion done by the agent.

This cannot be called at global scope and cached. It must be called for each separate web request at the time it is required.

newrelic.agent.get_browser_timing_footer() 

Returns the JavaScript footer to be included in HTML pages for page load timing. Useful for inserting the footer manually, rather than relying on the automatic insertion done by the agent.

This cannot be called at global scope and cached. It must be called for each separate web request at the time it is required.

For more help

Join the discussion about Python in the New Relic Online Technical Community! The Technical Community is a public platform to discuss and troubleshoot your New Relic toolset.

If you need additional help, get support at support.newrelic.com.