Skip to main content

Easily add metrics to your system – and actually understand them using automatically customized Prometheus queries

Project description

GitHub_headerImage

autometrics-py

A Python library that exports a decorator that makes it easy to understand the error rate, response time, and production usage of any function in your code. Jump straight from your IDE to live Prometheus charts for each HTTP/RPC handler, database method, or other piece of application logic.

Autometrics for Python provides:

  1. A decorator that can create Prometheus metrics for your functions and class methods throughout your code base.
  2. A helper function that will write corresponding Prometheus queries for you in a Markdown file.

See Why Autometrics? for more details on the ideas behind autometrics.

Features

  • autometrics decorator instruments any function or class method to track the most useful metrics
  • 💡 Writes Prometheus queries so you can understand the data generated without knowing PromQL
  • 🔗 Create links to live Prometheus charts directly into each functions docstrings (with tooltips coming soon!)
  • 📊 (Coming Soon!) Grafana dashboard showing the performance of all instrumented functions
  • 🚨 Enable Prometheus alerts using SLO best practices from simple annotations in your code
  • ⚡ Minimal runtime overhead

Using autometrics-py

  • Set up a Prometheus instance
  • Configure prometheus to scrape your application (check our instructions if you need help)
  • Include a .env file with your prometheus endpoint PROMETHEUS_URL=your endpoint. If this is not defined, the default endpoint will be http://localhost:9090/
  • pip install autometrics
  • Import the library in your code and use the decorator for any function:
from autometrics import autometrics

@autometrics
def sayHello:
   return "hello"
  • To access the PromQL queries for your decorated functions, run help(yourfunction) or print(yourfunction.__doc__).

  • To show tooltips over decorated functions in VSCode, with links to Prometheus queries, try installing the VSCode extension.

Note that we cannot support tooltips without a VSCode extension due to behavior of the static analyzer used in VSCode.

Alerts / SLOs

Autometrics makes it easy to add Prometheus alerts using Service-Level Objectives (SLOs) to a function or group of functions.

In order to receive alerts you need to add a set of rules to your Prometheus set up. You can find out more about those rules here: Prometheus alerting rules. Once added, most of the recording rules are dormant. They are enabled by specific metric labels that can be automatically attached by autometrics.

To use autometrics SLOs and alerts, create one or multiple Objectives based on the function(s) success rate and/or latency, as shown below. The Objective can be passed as an argument to the autometrics macro to include the given function in that objective.

from autometrics import autometrics
from autometrics.objectives import Objective, ObjectiveLatency, ObjectivePercentile

API_SLO = Objective(
    "random",
    success_rate=ObjectivePercentile.P99_9,
    latency=(ObjectiveLatency.Ms250, ObjectivePercentile.P99),
)

@autometrics(objective=API_SLO)
def api_handler():
  # ...

Autometrics by default will try to store information on which function calls a decorated function. As such you may want to place the autometrics in the top/first decorator, as otherwise you may get inner or wrapper as the caller function.

So instead of writing:

from functools import wraps
from typing import Any, TypeVar, Callable

R = TypeVar("R")

def noop(func: Callable[..., R]) -> Callable[..., R]:
    """A noop decorator that does nothing."""

    @wraps(func)
    def inner(*args: Any, **kwargs: Any) -> Any:
        return func(*args, **kwargs)

    return inner

@noop
@autometrics
def api_handler():
  # ...

You may want to switch the order of the decorator

@autometrics
@noop
def api_handler():
  # ...

Development of the package

This package uses poetry as a package manager, with all dependencies separated into three groups:

  • root level dependencies, required
  • dev, everything that is needed for development or in ci
  • examples, dependencies of everything in examples/ directory

By default, poetry will only install required dependencies, if you want to run examples, install using this command:

poetry install --with examples

Code in this repository is:

  • formatted using black.
  • contains type definitions (which are linted by pyright)
  • tested using pytest

In order to run these tools locally you have to install them, you can install them using poetry:

poetry install --with dev

After that you can run the tools individually

# Formatting using black
poetry run black .
# Lint using pyright
poetry run pyright
# Run the tests using pytest
poetry run pytest

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

autometrics-0.4.tar.gz (11.3 kB view hashes)

Uploaded Source

Built Distribution

autometrics-0.4-py3-none-any.whl (11.3 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page