Project Icon

autometrics-py

Python函数自动化监控与性能分析库

autometrics-py是一个Python库,为函数自动添加关键指标监控。它生成标准化指标和Prometheus查询,支持SLO定义、Grafana仪表盘集成和多种指标收集配置。这些功能有助于开发者快速识别和解决生产环境中的问题,提高代码可观测性。

GitHub_headerImage

Tests Discord Shield

A Python port of the Rust autometrics-rs library

Metrics 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.

Autometrics 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.

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 function's docstring
  • 🔍 Identify commits that introduced errors or increased latency
  • 🚨 Define alerts using SLO best practices directly in your source code
  • 📊 Grafana dashboards work out of the box to visualize the performance of instrumented functions & SLOs
  • ⚙️ Configurable metric collection library (opentelemetry or prometheus)
  • 📍 Attach exemplars to connect metrics with traces
  • ⚡ Minimal runtime overhead

Quickstart

  1. Add autometrics to your project's dependencies:
pip install autometrics
  1. Instrument your functions with the @autometrics decorator
from autometrics import autometrics

@autometrics
def my_function():
  # ...
  1. Configure autometrics by calling the init function:
from autometrics import init

init(tracker="prometheus", service_name="my-service")
  1. Export the metrics for Prometheus
# This example uses FastAPI, but you can use any web framework
from fastapi import FastAPI, Response
from prometheus_client import generate_latest

# Set up a metrics endpoint for Prometheus to scrape
#   `generate_latest` returns metrics data in the Prometheus text format
@app.get("/metrics")
def metrics():
    return Response(generate_latest())
  1. Run Prometheus locally with the Autometrics CLI or configure it manually to scrape your metrics endpoint
# Replace `8080` with the port that your app runs on
am start :8080
  1. (Optional) If you have Grafana, import the Autometrics dashboards for an overview and detailed view of all the function metrics you've collected

Using autometrics-py

  • You can import the library in your code and use the decorator for any function:
from autometrics import autometrics

@autometrics
def sayHello:
  return "hello"

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

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

  • You can also track the number of concurrent calls to a function by using the track_concurrency argument: @autometrics(track_concurrency=True).

    Note: Concurrency tracking is only supported when you set with the environment variable AUTOMETRICS_TRACKER=prometheus.

  • To access the PromQL queries for your decorated functions, run help(yourfunction) or print(yourfunction.__doc__).

    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/

Dashboards

Autometrics provides Grafana dashboards that will work for any project instrumented with the library.

Alerts / SLOs

Autometrics makes it easy to add intelligent alerting to your code, in order to catch increases in the error rate or latency across multiple functions.

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

# Create an objective for a high success rate
# Here, we want our API to have a success rate of 99.9%
API_SLO_HIGH_SUCCESS = Objective(
    "My API SLO for High Success Rate (99.9%)",
    success_rate=ObjectivePercentile.P99_9,
)

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

The 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.

Not sure what SLOs are? Check out our docs for an introduction.

In 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 to run Prometheus.

Already running Prometheus yourself? Read about how to load the autometrics alerting rules into Prometheus here.

Once the alerting rules are in Prometheus, you're ready to go.

To use autometrics SLOs and alerts, create one or multiple Objectives based on the function(s) success rate and/or latency, as shown above.

The Objective can be passed as an argument to the autometrics decorator, which will include the given function in that objective.

The example above used a success rate objective. (I.e., we wanted to be alerted when the error rate started to increase.)

You can also create an objective for the latency of your functions like so:

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

# Create an objective for low latency
#   - Functions with this objective should have a 99th percentile latency of less than 250ms
API_SLO_LOW_LATENCY = Objective(
    "My API SLO for Low Latency (99th percentile < 250ms)",
    latency=(ObjectiveLatency.Ms250, ObjectivePercentile.P99),
)

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

The caller Label

Autometrics 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".

This 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.

In the example above, this means that you could investigate the latency of the database queries that get_users makes, which is rather useful.

Settings and Configuration

Autometrics 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.

  • 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.
  • 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].
  • enable_exemplars - Enable exemplar collection. Default is
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

白日梦AI

白日梦AI提供专注于AI视频生成的多样化功能,包括文生视频、动态画面和形象生成等,帮助用户快速上手,创造专业级内容。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

讯飞绘镜

讯飞绘镜是一个支持从创意到完整视频创作的智能平台,用户可以快速生成视频素材并创作独特的音乐视频和故事。平台提供多样化的主题和精选作品,帮助用户探索创意灵感。

Project Cover

讯飞文书

讯飞文书依托讯飞星火大模型,为文书写作者提供从素材筹备到稿件撰写及审稿的全程支持。通过录音智记和以稿写稿等功能,满足事务性工作的高频需求,帮助撰稿人节省精力,提高效率,优化工作与生活。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号