{"id":15017932,"url":"https://github.com/autometrics-dev/autometrics-py","last_synced_at":"2025-10-11T11:02:38.442Z","repository":{"id":135068333,"uuid":"604121397","full_name":"autometrics-dev/autometrics-py","owner":"autometrics-dev","description":"Easily add metrics to your code that actually help you spot and debug issues in production. Built on Prometheus and OpenTelemetry.","archived":false,"fork":false,"pushed_at":"2024-03-16T10:02:37.000Z","size":1002,"stargazers_count":220,"open_issues_count":10,"forks_count":9,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-09-05T11:58:57.081Z","etag":null,"topics":["metrics","monitoring","observability","opentelemetry","prometheus","python","telemetry"],"latest_commit_sha":null,"homepage":"https://autometrics.dev","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/autometrics-dev.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE-APACHE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-02-20T11:32:41.000Z","updated_at":"2025-08-31T23:22:45.000Z","dependencies_parsed_at":"2023-10-14T23:22:44.820Z","dependency_job_id":"f40331cf-e4fd-4b1f-9564-6c2911256f40","html_url":"https://github.com/autometrics-dev/autometrics-py","commit_stats":{"total_commits":195,"total_committers":9,"mean_commits":"21.666666666666668","dds":0.6717948717948719,"last_synced_commit":"3b0e10c6975937ced1c1a7056aa8e8cbdecb9b20"},"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"purl":"pkg:github/autometrics-dev/autometrics-py","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/autometrics-dev%2Fautometrics-py","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/autometrics-dev%2Fautometrics-py/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/autometrics-dev%2Fautometrics-py/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/autometrics-dev%2Fautometrics-py/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/autometrics-dev","download_url":"https://codeload.github.com/autometrics-dev/autometrics-py/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/autometrics-dev%2Fautometrics-py/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279006916,"owners_count":26084217,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-11T02:00:06.511Z","response_time":55,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["metrics","monitoring","observability","opentelemetry","prometheus","python","telemetry"],"created_at":"2024-09-24T19:51:13.020Z","updated_at":"2025-10-11T11:02:38.397Z","avatar_url":"https://github.com/autometrics-dev.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"![GitHub_headerImage](https://user-images.githubusercontent.com/3262610/221191767-73b8a8d9-9f8b-440e-8ab6-75cb3c82f2bc.png)\n\n[![Tests](https://github.com/autometrics-dev/autometrics-py/actions/workflows/main.yml/badge.svg)](https://github.com/autometrics-dev/autometrics-py/actions/workflows/main.yml)\n[![Discord Shield](https://discordapp.com/api/guilds/950489382626951178/widget.png?style=shield)](https://discord.gg/kHtwcH8As9)\n\n\u003e A Python port of the Rust\n\u003e [autometrics-rs](https://github.com/fiberplane/autometrics-rs) library\n\nMetrics are a powerful and cost-efficient tool for understanding the health and performance of your code in production. But it's hard to decide what metrics to track and even harder to write queries to understand the data.\n\nAutometrics provides a decorator that makes it trivial to instrument any function with the most useful metrics: request rate, error rate, and latency. It standardizes these metrics and then generates powerful Prometheus queries based on your function details to help you quickly identify and debug issues in production.\n\nSee [Why Autometrics?](https://github.com/autometrics-dev#why-autometrics) for more details on the ideas behind autometrics.\n\n## Features\n\n- ✨ `@autometrics` decorator instruments any function or class method to track the\n  most useful metrics\n- 💡 Writes Prometheus queries so you can understand the data generated without\n  knowing PromQL\n- 🔗 Create links to live Prometheus charts directly into each function's docstring\n- 🔍 [Identify commits](#build-info) that introduced errors or increased latency\n- 🚨 [Define alerts](#alerts--slos) using SLO best practices directly in your source code\n- 📊 [Grafana dashboards](#dashboards) work out of the box to visualize the performance of instrumented functions \u0026 SLOs\n- ⚙️ [Configurable](#settings) metric collection library (`opentelemetry` or `prometheus`)\n- 📍 [Attach exemplars](#exemplars) to connect metrics with traces\n- ⚡ Minimal runtime overhead\n\n## Quickstart\n\n1. Add `autometrics` to your project's dependencies:\n\n```shell\npip install autometrics\n```\n\n2. Instrument your functions with the `@autometrics` decorator\n\n```python\nfrom autometrics import autometrics\n\n@autometrics\ndef my_function():\n  # ...\n```\n\n3. Configure autometrics by calling the `init` function:\n\n```python\nfrom autometrics import init\n\ninit(tracker=\"prometheus\", service_name=\"my-service\")\n```\n\n4. Export the metrics for Prometheus\n\n```python\n# This example uses FastAPI, but you can use any web framework\nfrom fastapi import FastAPI, Response\nfrom prometheus_client import generate_latest\n\n# Set up a metrics endpoint for Prometheus to scrape\n#   `generate_latest` returns metrics data in the Prometheus text format\n@app.get(\"/metrics\")\ndef metrics():\n    return Response(generate_latest())\n```\n\n5. Run Prometheus locally with the [Autometrics CLI](https://docs.autometrics.dev/local-development#getting-started-with-am) or [configure it manually](https://github.com/autometrics-dev#5-configuring-prometheus) to scrape your metrics endpoint\n\n```sh\n# Replace `8080` with the port that your app runs on\nam start :8080\n```\n\n6. (Optional) If you have Grafana, import the [Autometrics dashboards](https://github.com/autometrics-dev/autometrics-shared#dashboards) for an overview and detailed view of all the function metrics you've collected\n\n## Using `autometrics-py`\n\n- You can import the library in your code and use the decorator for any function:\n\n```python\nfrom autometrics import autometrics\n\n@autometrics\ndef sayHello:\n  return \"hello\"\n\n```\n\n- To show tooltips over decorated functions in VSCode, with links to Prometheus queries, try installing [the VSCode extension](https://marketplace.visualstudio.com/items?itemName=Fiberplane.autometrics).\n\n  \u003e **Note**: We cannot support tooltips without a VSCode extension due to behavior of the [static analyzer](https://github.com/davidhalter/jedi/issues/1921) used in VSCode.\n\n- You can also track the number of concurrent calls to a function by using the `track_concurrency` argument: `@autometrics(track_concurrency=True)`.\n\n  \u003e **Note**: Concurrency tracking is only supported when you set with the environment variable `AUTOMETRICS_TRACKER=prometheus`.\n\n- To access the PromQL queries for your decorated functions, run `help(yourfunction)` or `print(yourfunction.__doc__)`.\n\n  \u003e For these queries to work, include a `.env` file in your project with your prometheus endpoint `PROMETHEUS_URL=your endpoint`. If this is not defined, the default endpoint will be `http://localhost:9090/`\n\n## Dashboards\n\nAutometrics provides [Grafana dashboards](https://github.com/autometrics-dev/autometrics-shared#dashboards) that will work for any project instrumented with the library.\n\n## Alerts / SLOs\n\nAutometrics makes it easy to add intelligent alerting to your code, in order to catch increases in the error rate or latency across multiple functions.\n\n```python\nfrom autometrics import autometrics\nfrom autometrics.objectives import Objective, ObjectiveLatency, ObjectivePercentile\n\n# Create an objective for a high success rate\n# Here, we want our API to have a success rate of 99.9%\nAPI_SLO_HIGH_SUCCESS = Objective(\n    \"My API SLO for High Success Rate (99.9%)\",\n    success_rate=ObjectivePercentile.P99_9,\n)\n\n@autometrics(objective=API_SLO_HIGH_SUCCESS)\ndef api_handler():\n  # ...\n```\n\nThe library uses the concept of Service-Level Objectives (SLOs) to define the acceptable error rate and latency for groups of functions. Alerts will fire depending on the SLOs you set.\n\n\u003e Not sure what SLOs are? [Check out our docs](https://docs.autometrics.dev/slo) for an introduction.\n\nIn order to receive alerts, **you need to add a special set of rules to your Prometheus setup**. These are configured automatically when you use the [Autometrics CLI](https://docs.autometrics.dev/local-development#getting-started-with-am) to run Prometheus.\n\n\u003e Already running Prometheus yourself? [Read about how to load the autometrics alerting rules into Prometheus here](https://github.com/autometrics-dev/autometrics-shared#prometheus-recording--alerting-rules).\n\nOnce the alerting rules are in Prometheus, you're ready to go.\n\nTo use autometrics SLOs and alerts, create one or multiple `Objective`s based on the function(s) success rate and/or latency, as shown above.\n\nThe `Objective` can be passed as an argument to the `autometrics` decorator, which will include the given function in that objective.\n\nThe example above used a success rate objective. (I.e., we wanted to be alerted when the error rate started to increase.)\n\nYou can also create an objective for the latency of your functions like so:\n\n```python\nfrom autometrics import autometrics\nfrom autometrics.objectives import Objective, ObjectiveLatency, ObjectivePercentile\n\n# Create an objective for low latency\n#   - Functions with this objective should have a 99th percentile latency of less than 250ms\nAPI_SLO_LOW_LATENCY = Objective(\n    \"My API SLO for Low Latency (99th percentile \u003c 250ms)\",\n    latency=(ObjectiveLatency.Ms250, ObjectivePercentile.P99),\n)\n\n@autometrics(objective=API_SLO_LOW_LATENCY)\ndef api_handler():\n  # ...\n```\n\n## The `caller` Label\n\nAutometrics keeps track of instrumented functions that call each other. So, if you have a function `get_users` that calls another function `db.query`, then the metrics for latter will include a label `caller=\"get_users\"`.\n\nThis allows you to drill down into the metrics for functions that are _called by_ your instrumented functions, provided both of those functions are decorated with `@autometrics`.\n\nIn the example above, this means that you could investigate the latency of the database queries that `get_users` makes, which is rather useful.\n\n## Settings and Configuration\n\nAutometrics makes use of a number of environment variables to configure its behavior. All of them are also configurable with keyword arguments to the `init` function.\n\n- `tracker` - Configure the package that autometrics will use to produce metrics. Default is `opentelemetry`, but you can also use `prometheus`. Look in `pyproject.toml` for the corresponding versions of packages that will be used.\n- `histogram_buckets` - Configure the buckets used for latency histograms. Default is `[0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0]`.\n- `enable_exemplars` - Enable [exemplar collection](#exemplars). Default is `False`.\n- `service_name` - Configure the [service name](#service-name).\n- `version`, `commit`, `branch`, `repository_url`, `repository_provider` - Used to configure [build_info](#build-info).\n\nBelow is an example of initializing autometrics with build information, as well as the `prometheus` tracker. (Note that you can also accomplish the same confiugration with environment variables.)\n\n```python\nfrom autometrics import autometrics, init\nfrom git_utils import get_git_commit, get_git_branch\n\nVERSION = \"0.0.1\"\n\ninit(\n  tracker=\"prometheus\",\n  version=VERSION,\n  commit=get_git_commit(),\n  branch=get_git_branch()\n)\n```\n\n## Identifying commits that introduced problems \u003cspan name=\"build-info\" /\u003e\n\nAutometrics makes it easy to identify if a specific version or commit introduced errors or increased latencies.\n\n\u003e **NOTE** - As of writing, `build_info` will not work correctly when using the default setting of `AUTOMETRICS_TRACKER=opentelemetry`. If you wish to use `build_info`, you must use the `prometheus` tracker instead (`AUTOMETRICS_TRACKER=prometheus`).\n\u003e\n\u003e The issue will be fixed once the following PR is merged and released on the opentelemetry-python project: https://github.com/open-telemetry/opentelemetry-python/pull/3306\n\u003e\n\u003e autometrics-py will track support for build_info using the OpenTelemetry tracker via [this issue](https://github.com/autometrics-dev/autometrics-py/issues/38)\n\nThe library uses a separate metric (`build_info`) to track the version and git metadata of your code - repository url, provider name, commit and branch.\n\nIt then writes queries that group metrics by these metadata, so you can spot correlations between code changes and potential issues.\n\nConfigure these labels by setting the following environment variables:\n\n| Label                 | Run-Time Environment Variables        | Default value |\n| --------------------- | ------------------------------------- | ------------- |\n| `version`             | `AUTOMETRICS_VERSION`                 | `\"\"`          |\n| `commit`              | `AUTOMETRICS_COMMIT` or `COMMIT_SHA`  | `\"\"`          |\n| `branch`              | `AUTOMETRICS_BRANCH` or `BRANCH_NAME` | `\"\"`          |\n| `repository_url`      | `AUTOMETRICS_REPOSITORY_URL`          | `\"\"`\\*        |\n| `repository_provider` | `AUTOMETRICS_REPOSITORY_PROVIDER`     | `\"\"`\\*        |\n\n\\* Autometrics will attempt to automagically infer these values from the git config inside your working directory. To disable this behavior, explicitly set the corresponding setting or environment variable to `\"\"`.\n\nThis follows the method outlined in [Exposing the software version to Prometheus](https://www.robustperception.io/exposing-the-software-version-to-prometheus/).\n\n## Service name\n\nAll metrics produced by Autometrics have a label called `service.name` (or `service_name` when exported to Prometheus) attached, in order to identify the logical service they are part of.\n\nYou may want to override the default service name, for example if you are running multiple instances of the same code base as separate services, and you want to differentiate between the metrics produced by each one.\n\nThe service name is loaded from the following environment variables, in this order:\n\n1. `AUTOMETRICS_SERVICE_NAME` (at runtime)\n2. `OTEL_SERVICE_NAME` (at runtime)\n3. First part of `__package__` (at runtime)\n\n## Exemplars\n\n\u003e **NOTE** - As of writing, exemplars aren't supported by the default tracker (`AUTOMETRICS_TRACKER=opentelemetry`).\n\u003e You can track the progress of this feature here: https://github.com/autometrics-dev/autometrics-py/issues/41\n\nExemplars are a way to associate a metric sample to a trace by attaching `trace_id` and `span_id` to it. You can then use this information to jump from a metric to a trace in your tracing system (for example Jaeger). If you have an OpenTelemetry tracer configured, autometrics will automatically pick up the current span from it.\n\nTo use exemplars, you need to first switch to a tracker that supports them by setting `AUTOMETRICS_TRACKER=prometheus` and enable\nexemplar collection by setting `AUTOMETRICS_EXEMPLARS=true`. You also need to enable exemplars in Prometheus by launching Prometheus with the `--enable-feature=exemplar-storage` flag.\n\n## Exporting metrics\n\nThere are multiple ways to export metrics from your application, depending on your setup. You can see examples of how to do this in the [examples/export_metrics](https://github.com/autometrics-dev/autometrics-py/tree/main/examples/export_metrics) directory.\n\nIf you want to export metrics to Prometheus, you have two options in case of both `opentelemetry` and `prometheus` trackers:\n\n1. Create a route inside your app and respond with `generate_latest()`\n\n```python\n# This example uses FastAPI, but you can use any web framework\nfrom fastapi import FastAPI, Response\nfrom prometheus_client import generate_latest\n\n# Set up a metrics endpoint for Prometheus to scrape\n@app.get(\"/metrics\")\ndef metrics():\n    return Response(generate_latest())\n```\n\n2. Specify `prometheus` as the exporter type, and a separate server will be started to expose metrics from your app:\n\n```python\nexporter = {\n    \"type\": \"prometheus\",\n    \"address\": \"localhost\",\n    \"port\": 9464\n}\ninit(tracker=\"prometheus\", service_name=\"my-service\", exporter=exporter)\n```\n\nFor the OpenTelemetry tracker, you have more options, including a custom metric reader. You can specify the exporter type to be `otlp-proto-http` or `otlp-proto-grpc`, and metrics will be exported to a remote OpenTelemetry collector via the specified protocol. You will need to install the respective extra dependency in order for this to work, which you can do when you install autometrics:\n\n```sh\npip install autometrics[exporter-otlp-proto-http]\npip install autometrics[exporter-otlp-proto-grpc]\n```\n\nAfter installing it you can configure the exporter as follows:\n\n```python\nexporter = {\n    \"type\": \"otlp-proto-grpc\",\n    \"address\": \"http://localhost:4317\",\n    \"insecure\": True\n}\ninit(tracker=\"opentelemetry\", service_name=\"my-service\", exporter=exporter)\n```\n\nTo use a custom metric reader you can specify the exporter type to be `otel-custom` and provide a custom metric reader:\n\n```python\nmy_custom_metric_reader = PrometheusMetricReader(\"\")\nexporter = {\n    \"type\": \"otel-custom\",\n    \"reader\": my_custom_metric_reader\n}\ninit(tracker=\"opentelemetry\", service_name=\"my-service\", exporter=exporter)\n```\n\n## Development of the package\n\nThis package uses [poetry](https://python-poetry.org) as a package manager, with all dependencies separated into three groups:\n\n- root level dependencies, required\n- `dev`, everything that is needed for development or in ci\n- `examples`, dependencies of everything in `examples/` directory\n\nBy default, poetry will only install required dependencies, if you want to run examples, install using this command:\n\n```sh\npoetry install --with examples\n```\n\nCode in this repository is:\n\n- formatted using [black](https://black.readthedocs.io/en/stable/).\n- contains type definitions (which are linted by [mypy](https://www.mypy-lang.org/))\n- tested using [pytest](https://docs.pytest.org/)\n\nIn order to run these tools locally you have to install them, you can install them using poetry:\n\n```sh\npoetry install --with dev --all-extras\n```\n\nAfter that you can run the tools individually\n\n```sh\n# Formatting using black\npoetry run black .\n# Lint using mypy\npoetry run mypy .\n# Run the tests using pytest\npoetry run pytest\n# Run a single test, and clear the cache\npoetry run pytest --cache-clear -k test_tracker\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fautometrics-dev%2Fautometrics-py","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fautometrics-dev%2Fautometrics-py","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fautometrics-dev%2Fautometrics-py/lists"}