Skip to main content

Python

Supported platforms#

LinuxmacOSWindowsDocker

Profiling Python applications#

First, install pyroscope-io pip package:

pip install pyroscope-io

Minimal Configuration#

Add the following code to your application. This code will initialize pyroscope profiler and start profiling:

import pyroscope
pyroscope.configure(  application_name = "my.python.app", # replace this with some name for your application  server_address   = "http://my-pyroscope-server:4040", # replace this with the address of your pyroscope server)

Full Configuration#

Optionally, you can configure several parameters:

import pyroscope
pyroscope.configure(  application_name    = "my.python.app", # replace this with some name for your application  server_address      = "http://my-pyroscope-server:4040", # replace this with the address of your pyroscope server  auth_token          = "{YOUR_API_KEY}", # optional, if authentication is enabled, specify the API key  sample_rate         = 100, # default is 100  detect_subprocesses = False, # detect subprocesses started by the main process; default is False  oncpu               = True, # report cpu time only; default is True  native              = False, # profile native extensions; default is False  gil_only            = True, # only include traces for threads that are holding on to the Global Interpreter Lock; default is True  log_level           = "info", # default is info, possible values: trace, debug, info, warn, error and critical   tags           = {    "region":   '{os.getenv("REGION")}',  })

Tags#

You can add tags to certain parts of your code:

# You can use a wrapper:with pyroscope.tag_wrapper({ "controller": "slow_controller_i_want_to_profile" }):  slow_code()

Sending data to Phlare with Pyroscope Python integration#

Starting with weekly-f8 you can ingest pyroscope profiles directly to phlare.

import pyroscope
pyroscope.configure(    application_name = "phlare.python.app",    server_address = "<URL>",    basic_auth_username='<User>',    basic_auth_password='<Password>',    tenant_id="<TenantID>",)

To configure Python integration to send data to Phlare, replace the <URL> placeholder with the appropriate server URL. This could be the grafana.com Phlare URL or your own custom Phlare server URL.

If you need to send data to grafana.com, you'll have to configure HTTP Basic authentication. Replace <User> with your grafana.com stack user and <Password> with your grafana.com API key.

If your Phlare server has multi-tenancy enabled, you'll need to configure a tenant ID. Replace <TenantID> with your Phlare tenant ID.

Python profiling examples#

Check out the following resources to learn more about Python profiling:

Frame width represents CPU time per function
Pyroscope