Public API
editPublic API
editThe Elastic APM Python agent has several public APIs. Most of the public API functionality is not needed when using one of our supported frameworks, but they allow customized usage.
Client API
editThe public Client API consists of several methods on the Client
class.
This API can be used to track exceptions and log messages,
as well as to mark the beginning and end of transactions.
Instantiation
editTo create a Client
instance, import it and call its constructor:
from elasticapm import Client client = Client({'SERVICE_NAME': 'example'}, **defaults)
-
config
: A dictionary, with key/value configuration. For the possible configuration keys, see Configuration. -
**defaults
: default values for configuration. These can be omitted in most cases, and take the least precedence.
Errors
editClient.capture_exception()
editCaptures an exception object:
try: x = int("five") except ValueError: client.capture_exception()
-
exc_info
: A(type, value, traceback)
tuple as returned bysys.exc_info()
. If not provided, it will be captured automatically. -
date
: Adatetime.datetime
object representing the occurrence time of the error. If left empty, it defaults todatetime.datetime.utcnow()
. -
context
: A dictionary with contextual information. This dictionary must follow the Context schema definition. -
custom
: A dictionary of custom data you want to attach to the event. -
handled
: A boolean to indicate if this exception was handled or not.
Returns the id of the error as a string.
Client.capture_message()
editCaptures a message with optional added contextual data. Example:
client.capture_message('Billing process succeeded.')
-
message
: The message as a string. -
param_message
: Alternatively, a parameterized message as a dictionary. The dictionary contains two values:message
, andparams
. This allows the APM server to group messages together that share the same parameterized message. Example:client.capture_message(param_message={ 'message': 'Billing process for %s succeeded. Amount: %s', 'params': (customer.id, order.total_amount), })
-
stack
: If set toTrue
(the default), a stacktrace from the call site will be captured. -
exc_info
: A(type, value, traceback)
tuple as returned bysys.exc_info()
. If not provided, it will be captured automatically, ifcapture_message()
was called in anexcept
block. -
date
: Adatetime.datetime
object representing the occurrence time of the error. If left empty, it defaults todatetime.datetime.utcnow()
. -
context
: A dictionary with contextual information. This dictionary must follow the Context schema definition. -
custom
: A dictionary of custom data you want to attach to the event.
Returns the id of the message as a string.
Either the message
or the param_message
argument is required.
Transactions
editClient.begin_transaction()
editBegin tracking a transaction. Should be called e.g. at the beginning of a request or when starting a background task. Example:
client.begin_transaction('processors')
-
transaction_type
: (required) A string describing the type of the transaction, e.g.'request'
or'celery'
.
Client.end_transaction()
editEnd tracking the transaction. Should be called e.g. at the end of a request or when ending a background task. Example:
client.end_transaction('myapp.billing_process', processor.status)
-
name
: (optional) A string describing the name of the transaction, e.g.process_order
. This is typically the name of the view/controller that handles the request, or the route name. -
result
: (optional) A string describing the result of the transaction. This is typically the HTTP status code, or e.g.'success'
for a background task.
if name
and result
are not set in the end_transaction()
call,
they have to be set beforehand by calling elasticapm.set_transaction_name()
and elasticapm.set_transaction_result()
during the transaction.
Other APIs
editelasticapm.instrument()
editInstruments libraries automatically.
This includes a wide range of standard library and 3rd party modules.
A list of instrumented modules can be found in elasticapm.instrumentation.register
.
This function should be called as early as possibly in the startup of your application.
For supported frameworks, this is called automatically. Example:
import elasticapm elasticapm.instrument()
elasticapm.set_transaction_name()
editSet the name of the current transaction. For supported frameworks, the transaction name is determined automatically, and can be overridden using this function. Example:
import elasticapm elasticapm.set_transaction_name('myapp.billing_process')
-
name
: (required) A string describing name of the transaction -
override
: ifTrue
(the default), overrides any previously set transaction name. IfFalse
, only sets the name if the transaction name hasn’t already been set.
elasticapm.set_transaction_result()
editSet the name of the current transaction. For supported frameworks, the transaction result is determined automatically, and can be overridden using this function. Example:
import elasticapm elasticapm.set_transaction_result('SUCCESS')
-
result
: (required) A string describing the result of the transaction, e.g.HTTP 2xx
orSUCCESS
-
override
: ifTrue
(the default), overrides any previously set result. IfFalse
, only sets the result if the result hasn’t already been set.
elasticapm.set_custom_context()
editAttach custom contextual data to the current transaction and errors. Supported frameworks will automatically attach information about the HTTP request and the logged in user. You can attach further data using this function. Example:
import elasticapm elasticapm.set_custom_context({'billing_amount': product.price * item_count})
-
data
: (required) A dictionary with the data to be attached. This should be a flat key/valuedict
object.
.
, *
, and "
are invalid characters for key names and will be replaced with _
.
Errors that happen after this call will also have the custom context attached to them.
You can call this function multiple times, new context data will be merged with existing data,
following the update()
semantics of Python dictionaries.
elasticapm.set_user_context()
editAttach information about the currently logged in user to the current transaction and errors. Example:
import elasticapm elasticapm.set_user_context(username=user.username, email=user.email, user_id=user.id)
-
username
: The username of the logged in user -
email
: The email of the logged in user -
user_id
: The unique identifier of the logged in user, e.g. the primary key value
Errors that happen after this call will also have the user context attached to them.
You can call this function multiple times, new user data will be merged with existing data,
following the update()
semantics of Python dictionaries.
elasticapm.capture_span
editCapture a custom span.
This can be used either as a function decorator or as a context manager (in a with
statement).
When used as a decorator, the name of the span will be set to the name of the function.
When used as a context manager, a name has to be provided.
import elasticapm @elasticapm.capture_span() def coffee_maker(strength): fetch_water() with elasticapm.capture_span('near-to-machine', tags={"type": "arabica"}): insert_filter() for i in range(strengh): pour_coffee() start_drip() fresh_pots()
-
name
: The name of the span -
span_type
: The type of the span, usually in a dot-separated hierarchy oftype
,subtype
, andaction
, e.g.db.mysql.query
-
skip_frames
: The number of stack frames to skip when collecting stack traces. Defaults to0
. -
leaf
: ifTrue
, all spans nested bellow this span will be ignored. Defaults toFalse
. -
tags
: a dictionary of tags. Both keys and values must be strings. Defaults toNone
.
elasticapm.tag()
editAttach tags to the the current transaction and errors. Example:
import elasticapm elasticapm.tag(ecommerce=True, dollar_value=47.12)
Errors that happen after this call will also have the tags attached to them.
You can call this function multiple times, new tags will be merged with existing tags,
following the update()
semantics of Python dictionaries.
The value is converted to a string.
.
, *
, and "
are invalid characters for tag names and will be replaced with _
.