aioprometheus


Nameaioprometheus JSON
Version 23.12.0 PyPI version JSON
download
home_pagehttps://github.com/claws/aioprometheus
SummaryA Prometheus Python client library for asyncio-based applications
upload_time2023-12-27 23:54:29
maintainer
docs_urlNone
authorChris Laws
requires_python>=3.8.0
licenseMIT
keywords prometheus monitoring metrics
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            aioprometheus
=============

|ci status| |pypi| |python| |cov| |docs| |license|

`aioprometheus` is a Prometheus Python client library for asyncio-based
applications. It provides metrics collection and serving capabilities for
use with Prometheus and compatible monitoring systems. It supports exporting
metrics into text and pushing metrics to a gateway.

The ASGI middleware in `aioprometheus` can be used in FastAPI/Starlette and
Quart applications. `aioprometheus` can also be used in other kinds of asyncio
applications too.

The project documentation can be found on
`ReadTheDocs <http://aioprometheus.readthedocs.org/>`_.


Install
-------

.. code-block:: console

    $ pip install aioprometheus

The ASGI middleware does not have any external dependencies but the Starlette
and Quart convenience functions that handle metrics requests do.

If you plan on using the ASGI middleware in a Starlette / FastAPI application
then you can install the extra dependencies alongside `aioprometheus` by adding
extras to the install.

.. code-block:: console

    $ pip install aioprometheus[starlette]

If you plan on using the ASGI middleware in a Quart application then you can
install the extra dependencies alongside `aioprometheus` by adding extras
to the install.

.. code-block:: console

    $ pip install aioprometheus[quart]

A Prometheus Push Gateway client and a HTTP service are included, but their
dependencies are not installed by default. You can install them alongside
`aioprometheus` by adding extras to the install.

.. code-block:: console

    $ pip install aioprometheus[aiohttp]

Multiple optional dependencies can be listed at once, such as:

.. code-block:: console

    $ pip install aioprometheus[aiohttp,starlette,quart]


Usage
-----

There are two basic steps involved in using aioprometheus; the first is to
instrument your software by creating metrics to monitor events and the second
is to expose the metrics to a collector.

Creating a new metric is easy. First, import the appropriate metric from
aioprometheus. In the example below it's a Counter metric. Next, instantiate
the metric with a name and a help string. Finally, update the metric when an
event occurs. In this case the counter is incremented.

.. code-block:: python

    from aioprometheus import Counter

    events_counter = Counter(
        "events_counter",
        "Total number of events.",
    )

    events_counter.inc({"kind": "event A"})

By default, metrics get registered into the default collector registry which
is available at ``aioprometheus.REGISTRY``.

A number of convenience decorator functions are included in aioprometheus that
can assist with automatically updating metrics. The ``examples`` directory
contains various decorators examples.

Once your software is instrumented with various metrics you'll want to
expose them to Prometheus or a compatible metrics collector. There are
multiple strategies available for this and the right choice depends on the
kind of thing being instrumented.

If you are instrumenting a Starlette, FastAPI or Quart application then the
easiest option for adding Prometheus metrics is to use the ASGI Middleware
provided by `aioprometheus`.

The ASGI middleware provides a default set of metrics that include counters
for total requests received, total responses sent, exceptions raised and
response status codes for route handlers.

The example below shows how to use the aioprometheus ASGI middleware in a
FastAPI application. FastAPI is built upon Starlette so using the middleware
in Starlette would be the same.

.. code-block:: python

    from fastapi import FastAPI, Request, Response

    from aioprometheus import Counter, MetricsMiddleware
    from aioprometheus.asgi.starlette import metrics

    app = FastAPI()

    # Any custom application metrics are automatically included in the exposed
    # metrics. It is a good idea to attach the metrics to 'app.state' so they
    # can easily be accessed in the route handler - as metrics are often
    # created in a different module than where they are used.
    app.state.users_events_counter = Counter("events", "Number of events.")

    app.add_middleware(MetricsMiddleware)
    app.add_route("/metrics", metrics)


    @app.get("/")
    async def root(request: Request):
        return Response("FastAPI Middleware Example")


    @app.get("/users/{user_id}")
    async def get_user(
        request: Request,
        user_id: str,
    ):
        request.app.state.users_events_counter.inc({"path": request.scope["path"]})
        return Response(f"{user_id}")


    if __name__ == "__main__":
        import uvicorn

        uvicorn.run(app)


Other examples in the ``examples/frameworks`` directory show how aioprometheus
can be used within various web application frameworks.

The next example shows how to use the Service HTTP endpoint to provide a
dedicated metrics endpoint for other applications such as long running
distributed system processes.

The Service object requires optional extras to be installed so make sure you
install aioprometheus with the 'aiohttp' extras.

.. code-block:: console

    $ pip install aioprometheus[aiohttp]

.. code-block:: python

    """
    This example demonstrates how the ``aioprometheus.Service`` can be used to
    expose metrics on a HTTP endpoint.

    .. code-block:: console

        (env) $ python simple-service-example.py
        Serving prometheus metrics on: http://127.0.0.1:8000/metrics

    You can open the URL in a browser or use the ``curl`` command line tool to
    fetch metrics manually to verify they can be retrieved by Prometheus server.

    """

    import asyncio
    import socket

    from aioprometheus import Counter
    from aioprometheus.service import Service


    async def main():

        service = Service()
        events_counter = Counter(
            "events", "Number of events.", const_labels={"host": socket.gethostname()}
        )

        await service.start(addr="127.0.0.1", port=8000)
        print(f"Serving prometheus metrics on: {service.metrics_url}")

        # Now start another coroutine to periodically update a metric to
        # simulate the application making some progress.
        async def updater(c: Counter):
            while True:
                c.inc({"kind": "timer_expiry"})
                await asyncio.sleep(1.0)

        await updater(events_counter)

        # Finally stop server
        await service.stop()


    if __name__ == "__main__":

        try:
            asyncio.run(main())
        except KeyboardInterrupt:
            pass

A counter metric is used to track the number of while loop iterations executed
by the 'updater' coroutine. The Service is started and then a coroutine is
started to periodically update the metric to simulate progress.

The Service can be configured to bind to a user defined network interface and
port.

When the Service receives a request for metrics it forms a response by
rendering the contents of its registry into the appropriate format. By default
the Service uses the default collector registry, which is
``aioprometheus.REGISTRY``. The Service can be configured to use a different
registry by passing one in as an argument to the Service constructor.


License
-------

`aioprometheus` is released under the MIT license.

`aioprometheus` originates from the (now deprecated)
`prometheus python <https://github.com/slok/prometheus-python>`_ package which
was released under the MIT license. `aioprometheus` continues to use the MIT
license and contains a copy of the original MIT license from the
`prometheus-python` project as instructed by the original license.


.. |ci status| image:: https://github.com/claws/aioprometheus/workflows/CI%20Pipeline/badge.svg?branch=master
    :target: https://github.com/claws/aioprometheus/actions?query=branch%3Amaster

.. |pypi| image:: https://img.shields.io/pypi/v/aioprometheus.svg
    :target: https://pypi.python.org/pypi/aioprometheus

.. |python| image:: https://img.shields.io/pypi/pyversions/aioprometheus.svg
    :target: https://pypi.python.org/pypi/aioprometheus/

.. |cov| image:: https://codecov.io/github/claws/aioprometheus/branch/master/graph/badge.svg?token=oPPBg8hBgc
    :target: https://codecov.io/github/claws/aioprometheus

.. |docs| image:: https://readthedocs.org/projects/aioprometheus/badge/?version=latest
    :target: https://aioprometheus.readthedocs.io/en/latest

.. |license| image:: https://img.shields.io/badge/license-MIT-blue.svg
    :target: https://github.com/claws/aioprometheus/License/LICENSE

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/claws/aioprometheus",
    "name": "aioprometheus",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8.0",
    "maintainer_email": "",
    "keywords": "prometheus,monitoring,metrics",
    "author": "Chris Laws",
    "author_email": "clawsicus@gmail.com",
    "download_url": "",
    "platform": null,
    "description": "aioprometheus\n=============\n\n|ci status| |pypi| |python| |cov| |docs| |license|\n\n`aioprometheus` is a Prometheus Python client library for asyncio-based\napplications. It provides metrics collection and serving capabilities for\nuse with Prometheus and compatible monitoring systems. It supports exporting\nmetrics into text and pushing metrics to a gateway.\n\nThe ASGI middleware in `aioprometheus` can be used in FastAPI/Starlette and\nQuart applications. `aioprometheus` can also be used in other kinds of asyncio\napplications too.\n\nThe project documentation can be found on\n`ReadTheDocs <http://aioprometheus.readthedocs.org/>`_.\n\n\nInstall\n-------\n\n.. code-block:: console\n\n    $ pip install aioprometheus\n\nThe ASGI middleware does not have any external dependencies but the Starlette\nand Quart convenience functions that handle metrics requests do.\n\nIf you plan on using the ASGI middleware in a Starlette / FastAPI application\nthen you can install the extra dependencies alongside `aioprometheus` by adding\nextras to the install.\n\n.. code-block:: console\n\n    $ pip install aioprometheus[starlette]\n\nIf you plan on using the ASGI middleware in a Quart application then you can\ninstall the extra dependencies alongside `aioprometheus` by adding extras\nto the install.\n\n.. code-block:: console\n\n    $ pip install aioprometheus[quart]\n\nA Prometheus Push Gateway client and a HTTP service are included, but their\ndependencies are not installed by default. You can install them alongside\n`aioprometheus` by adding extras to the install.\n\n.. code-block:: console\n\n    $ pip install aioprometheus[aiohttp]\n\nMultiple optional dependencies can be listed at once, such as:\n\n.. code-block:: console\n\n    $ pip install aioprometheus[aiohttp,starlette,quart]\n\n\nUsage\n-----\n\nThere are two basic steps involved in using aioprometheus; the first is to\ninstrument your software by creating metrics to monitor events and the second\nis to expose the metrics to a collector.\n\nCreating a new metric is easy. First, import the appropriate metric from\naioprometheus. In the example below it's a Counter metric. Next, instantiate\nthe metric with a name and a help string. Finally, update the metric when an\nevent occurs. In this case the counter is incremented.\n\n.. code-block:: python\n\n    from aioprometheus import Counter\n\n    events_counter = Counter(\n        \"events_counter\",\n        \"Total number of events.\",\n    )\n\n    events_counter.inc({\"kind\": \"event A\"})\n\nBy default, metrics get registered into the default collector registry which\nis available at ``aioprometheus.REGISTRY``.\n\nA number of convenience decorator functions are included in aioprometheus that\ncan assist with automatically updating metrics. The ``examples`` directory\ncontains various decorators examples.\n\nOnce your software is instrumented with various metrics you'll want to\nexpose them to Prometheus or a compatible metrics collector. There are\nmultiple strategies available for this and the right choice depends on the\nkind of thing being instrumented.\n\nIf you are instrumenting a Starlette, FastAPI or Quart application then the\neasiest option for adding Prometheus metrics is to use the ASGI Middleware\nprovided by `aioprometheus`.\n\nThe ASGI middleware provides a default set of metrics that include counters\nfor total requests received, total responses sent, exceptions raised and\nresponse status codes for route handlers.\n\nThe example below shows how to use the aioprometheus ASGI middleware in a\nFastAPI application. FastAPI is built upon Starlette so using the middleware\nin Starlette would be the same.\n\n.. code-block:: python\n\n    from fastapi import FastAPI, Request, Response\n\n    from aioprometheus import Counter, MetricsMiddleware\n    from aioprometheus.asgi.starlette import metrics\n\n    app = FastAPI()\n\n    # Any custom application metrics are automatically included in the exposed\n    # metrics. It is a good idea to attach the metrics to 'app.state' so they\n    # can easily be accessed in the route handler - as metrics are often\n    # created in a different module than where they are used.\n    app.state.users_events_counter = Counter(\"events\", \"Number of events.\")\n\n    app.add_middleware(MetricsMiddleware)\n    app.add_route(\"/metrics\", metrics)\n\n\n    @app.get(\"/\")\n    async def root(request: Request):\n        return Response(\"FastAPI Middleware Example\")\n\n\n    @app.get(\"/users/{user_id}\")\n    async def get_user(\n        request: Request,\n        user_id: str,\n    ):\n        request.app.state.users_events_counter.inc({\"path\": request.scope[\"path\"]})\n        return Response(f\"{user_id}\")\n\n\n    if __name__ == \"__main__\":\n        import uvicorn\n\n        uvicorn.run(app)\n\n\nOther examples in the ``examples/frameworks`` directory show how aioprometheus\ncan be used within various web application frameworks.\n\nThe next example shows how to use the Service HTTP endpoint to provide a\ndedicated metrics endpoint for other applications such as long running\ndistributed system processes.\n\nThe Service object requires optional extras to be installed so make sure you\ninstall aioprometheus with the 'aiohttp' extras.\n\n.. code-block:: console\n\n    $ pip install aioprometheus[aiohttp]\n\n.. code-block:: python\n\n    \"\"\"\n    This example demonstrates how the ``aioprometheus.Service`` can be used to\n    expose metrics on a HTTP endpoint.\n\n    .. code-block:: console\n\n        (env) $ python simple-service-example.py\n        Serving prometheus metrics on: http://127.0.0.1:8000/metrics\n\n    You can open the URL in a browser or use the ``curl`` command line tool to\n    fetch metrics manually to verify they can be retrieved by Prometheus server.\n\n    \"\"\"\n\n    import asyncio\n    import socket\n\n    from aioprometheus import Counter\n    from aioprometheus.service import Service\n\n\n    async def main():\n\n        service = Service()\n        events_counter = Counter(\n            \"events\", \"Number of events.\", const_labels={\"host\": socket.gethostname()}\n        )\n\n        await service.start(addr=\"127.0.0.1\", port=8000)\n        print(f\"Serving prometheus metrics on: {service.metrics_url}\")\n\n        # Now start another coroutine to periodically update a metric to\n        # simulate the application making some progress.\n        async def updater(c: Counter):\n            while True:\n                c.inc({\"kind\": \"timer_expiry\"})\n                await asyncio.sleep(1.0)\n\n        await updater(events_counter)\n\n        # Finally stop server\n        await service.stop()\n\n\n    if __name__ == \"__main__\":\n\n        try:\n            asyncio.run(main())\n        except KeyboardInterrupt:\n            pass\n\nA counter metric is used to track the number of while loop iterations executed\nby the 'updater' coroutine. The Service is started and then a coroutine is\nstarted to periodically update the metric to simulate progress.\n\nThe Service can be configured to bind to a user defined network interface and\nport.\n\nWhen the Service receives a request for metrics it forms a response by\nrendering the contents of its registry into the appropriate format. By default\nthe Service uses the default collector registry, which is\n``aioprometheus.REGISTRY``. The Service can be configured to use a different\nregistry by passing one in as an argument to the Service constructor.\n\n\nLicense\n-------\n\n`aioprometheus` is released under the MIT license.\n\n`aioprometheus` originates from the (now deprecated)\n`prometheus python <https://github.com/slok/prometheus-python>`_ package which\nwas released under the MIT license. `aioprometheus` continues to use the MIT\nlicense and contains a copy of the original MIT license from the\n`prometheus-python` project as instructed by the original license.\n\n\n.. |ci status| image:: https://github.com/claws/aioprometheus/workflows/CI%20Pipeline/badge.svg?branch=master\n    :target: https://github.com/claws/aioprometheus/actions?query=branch%3Amaster\n\n.. |pypi| image:: https://img.shields.io/pypi/v/aioprometheus.svg\n    :target: https://pypi.python.org/pypi/aioprometheus\n\n.. |python| image:: https://img.shields.io/pypi/pyversions/aioprometheus.svg\n    :target: https://pypi.python.org/pypi/aioprometheus/\n\n.. |cov| image:: https://codecov.io/github/claws/aioprometheus/branch/master/graph/badge.svg?token=oPPBg8hBgc\n    :target: https://codecov.io/github/claws/aioprometheus\n\n.. |docs| image:: https://readthedocs.org/projects/aioprometheus/badge/?version=latest\n    :target: https://aioprometheus.readthedocs.io/en/latest\n\n.. |license| image:: https://img.shields.io/badge/license-MIT-blue.svg\n    :target: https://github.com/claws/aioprometheus/License/LICENSE\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A Prometheus Python client library for asyncio-based applications",
    "version": "23.12.0",
    "project_urls": {
        "Homepage": "https://github.com/claws/aioprometheus"
    },
    "split_keywords": [
        "prometheus",
        "monitoring",
        "metrics"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "9121c9e882ea8a7189b7d71ffb709db24708113896e81a25e074a17f9874d8be",
                "md5": "fde7b35db8b7d963e50000cc64adb978",
                "sha256": "b1a77259131153ef820b494e76439b278434eaf2a5e25dc0b8bf3d835f455960"
            },
            "downloads": -1,
            "filename": "aioprometheus-23.12.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "fde7b35db8b7d963e50000cc64adb978",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8.0",
            "size": 31711,
            "upload_time": "2023-12-27T23:54:29",
            "upload_time_iso_8601": "2023-12-27T23:54:29.097297Z",
            "url": "https://files.pythonhosted.org/packages/91/21/c9e882ea8a7189b7d71ffb709db24708113896e81a25e074a17f9874d8be/aioprometheus-23.12.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-12-27 23:54:29",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "claws",
    "github_project": "aioprometheus",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "requirements": [],
    "lcname": "aioprometheus"
}
        
Elapsed time: 0.16720s