### Install Task Runner Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/task.md Installs the Task runner using Homebrew. Other installation methods are available. ```bash brew install go-task ``` -------------------------------- ### Start FastAPI App with Uvicorn Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/examples/default-metrics-diff-labels/README.md Use Uvicorn to start the FastAPI application. Ensure you have installed dependencies and activated your virtual environment. ```python uvicorn main:app ``` -------------------------------- ### Instrument and Expose App with Defaults Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/README.md Instrument your FastAPI app with default metrics and expose them. This is the quickest way to get started. ```python Instrumentator().instrument(app).expose(app) ``` -------------------------------- ### Install Git Hooks with Pre-Commit Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/pre-commit.md Install pre-commit hooks for all commit types. This command should be run after cloning the repository. ```bash pre-commit install --install-hooks ``` ```bash pre-commit install --install-hooks --hook-type commit-msg ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/DEVELOPMENT.md Set up pre-commit hooks for the project. This ensures code quality and consistency before commits. Run 'pre-commit run -a' to execute all hooks. ```sh pre-commit install --install-hooks ``` ```sh pre-commit install --install-hooks --hook-type commit-msg ``` ```sh pre-commit run -a ``` -------------------------------- ### Install Python Dependencies with Poetry Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/DEVELOPMENT.md Use this command after cloning the repository to install project dependencies managed by Poetry. Refer to devel/poetry.md for more details. ```sh poetry install ``` -------------------------------- ### Example Prometheus Metrics Output Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/examples/prom-multi-proc-gunicorn/README.md This is an example of the metrics output you might see. Note the absence of certain metrics like 'created_by' and system-level metrics (CPU, memory) which are not supported in multi-process mode. ```txt # TYPE ping_total counter ping_total 5.0 # HELP metrics_total Number of metrics calls. # TYPE metrics_total counter metrics_total 1.0 # HELP main_total Counts of main executions. # TYPE main_total counter main_total 2.0 ``` -------------------------------- ### Example Metric with Namespace and Subsystem Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/README.md Illustrates how metrics appear in Prometheus when a namespace and subsystem are specified. ```sh # TYPE myproject_myservice_http_request_duration_highr_seconds histogram myproject_myservice_http_request_duration_highr_seconds_bucket{le="0.01"} 0.0 ``` -------------------------------- ### Add Poetry Plugin Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/poetry.md Installs a Poetry plugin, such as 'poetry-plugin-up', which can automate dependency updates. ```bash poetry self add poetry-plugin-up ``` -------------------------------- ### Start Gunicorn with Uvicorn Workers Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/examples/prom-multi-proc-gunicorn/README.md Start the FastAPI application using Gunicorn with two Uvicorn workers. Ensure the Prometheus multi-process directory is clean and created before starting. ```shell rm -rf "$PROMETHEUS_MULTIPROC_DIR" mkdir -p "$PROMETHEUS_MULTIPROC_DIR" gunicorn main:app \ --config gunicorn.conf.py \ --workers 2 \ --worker-class uvicorn.workers.UvicornWorker \ --bind 0.0.0.0:8080 ``` -------------------------------- ### Run Project Tests with Task Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/DEVELOPMENT.md Execute all project tests using the Task runner to verify the setup. Consult devel/task.md for further information on Task usage. ```sh task test ``` -------------------------------- ### Update Poetry Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/poetry.md Updates the Poetry installation itself to the latest version. ```bash poetry self update ``` -------------------------------- ### Set Prometheus Multi-process Directory Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/examples/prom-multi-proc-gunicorn/README.md Set the environment variable PROMETHEUS_MULTIPROC_DIR to an unused location before starting Gunicorn. This is required for the Prometheus client library to manage metrics across multiple processes. ```shell export PROMETHEUS_MULTIPROC_DIR=/tmp/python-testing-pfi/560223ba-887f-429a-9c48-933df56a68ba ``` -------------------------------- ### Instrument and Expose App on Startup Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/README.md An alternative method to instrument and expose metrics, particularly useful if app modifications are needed during startup. The metrics are exposed during the application's startup event. ```python instrumentator = Instrumentator().instrument(app) @app.on_event("startup") async def _startup(): instrumentator.expose(app) ``` -------------------------------- ### Monitor Release Workflow Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/RELEASE.md Open the release workflow in the web interface to monitor its progress. This workflow handles building and publishing the package. ```shell gh workflow view release --web ``` -------------------------------- ### Run Pre-Commit Against All Files Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/pre-commit.md Execute all configured pre-commit hooks against every file in the repository. Useful for a full code quality check. ```bash pre-commit run -a ``` -------------------------------- ### List Available Tasks Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/task.md Lists all available tasks defined in the Taskfile.yaml. ```bash task --list ``` -------------------------------- ### Prepare Release Commit Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/RELEASE.md Stage all relevant files for the release, including the changelog, version updates, and configuration files. Commit the changes with a signed commit message. ```shell git add CHANGELOG.md src/*/__init__.py pyproject.toml ``` ```shell git commit -S -m "chore: Prepare release v$VERSION" ``` ```shell git log --show-signature -1 ``` -------------------------------- ### Run Specific Hook Against All Files Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/pre-commit.md Execute a particular pre-commit hook against all files in the repository. Replace `` with the desired hook's identifier. ```bash pre-commit run -a ``` -------------------------------- ### Run a Specific Task Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/task.md Executes a specified task. Replace '' with the name of the task to run. ```bash task ``` -------------------------------- ### Bump Version with Poetry Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/RELEASE.md Use Poetry to formally bump the package version. This command updates relevant files like pyproject.toml. ```shell poetry version $VERSION ``` -------------------------------- ### Interact with FastAPI App and Fetch Metrics Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/examples/prom-multi-proc-gunicorn/README.md Send requests to the /ping endpoint multiple times and then fetch the metrics from the /metrics endpoint. This helps in observing the collected metrics. ```shell for i in {1..5}; do curl localhost:8080/ping; done curl localhost:8080/metrics ``` -------------------------------- ### Activate Poetry Environment Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/poetry.md Activates the virtual environment created by Poetry, allowing you to run commands within it directly. ```bash poetry shell ``` -------------------------------- ### Create Instrumentator Instance Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/README.md Instantiate the Instrumentator with advanced configuration options like grouping status codes, ignoring untemplated routes, and respecting environment variables for instrumentation. ```python from prometheus_fastapi_instrumentator import Instrumentator, metrics instrumentator = Instrumentator( should_group_status_codes=False, should_ignore_untemplated=True, should_respect_env_var=True, should_instrument_requests_inprogress=True, excluded_handlers=[ ".*admin.*", "/metrics"], env_var_name="ENABLE_METRICS", inprogress_name="inprogress", inprogress_labels=True ) ``` -------------------------------- ### Add Request and Response Size Metrics Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/README.md Configures and adds metrics for tracking request and response sizes, with options to include handler, method, and status, along with custom namespaces, subsystems, and labels. ```python instrumentator.add( metrics.request_size( should_include_handler=True, should_include_method=False, should_include_status=True, metric_namespace="a", metric_subsystem="b", custom_labels={"service": "example-label"} ) ).add( metrics.response_size( should_include_handler=True, should_include_method=False, should_include_status=True, metric_namespace="namespace", metric_subsystem="subsystem", custom_labels={"service": "example-label"} ) ) ``` -------------------------------- ### Expose Metrics Endpoint with Gzip Compression Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/README.md Serve metrics on a FastAPI endpoint. The `expose` method adds an endpoint, and `should_gzip=True` enables compression for efficient data transfer. ```python instrumentator.expose(app, include_in_schema=False, should_gzip=True) ``` -------------------------------- ### Perform Basic Instrumentation Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/README.md Register the instrumentation with the FastAPI application. This method should be called after constructing the instrumentator object. ```python instrumentator.instrument(app) ``` -------------------------------- ### Set Release Version Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/RELEASE.md Set the desired version number for the release. This follows Semantic Versioning. ```shell VERSION=1.0.1 ``` -------------------------------- ### Run Commands within Poetry Environment Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/poetry.md Executes a command within the context of the Poetry-managed virtual environment without explicitly activating it. ```bash poetry run ``` -------------------------------- ### Specify Namespace and Subsystem Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/README.md Set the namespace and subsystem for metrics during instrumentation. This helps organize metrics, especially in larger projects. ```python Instrumentator().instrument( app, metric_namespace="myproject", metric_subsystem="myservice", ).expose(app) ``` ```python Instrumentator().add( metrics.default( metric_namespace="myproject", metric_subsystem="myservice", ), ).instrument(app).expose(app) ``` -------------------------------- ### Update Project Dependencies Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/poetry.md Uses the 'poetry-plugin-up' to automatically update project dependencies and bump versions in pyproject.toml. ```bash poetry up ``` -------------------------------- ### Push Changes to Master Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/RELEASE.md Push the prepared release commit to the master branch. This action may trigger CI/CD pipelines. ```shell git push origin master ``` -------------------------------- ### Tag Latest Commit Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/RELEASE.md Create an annotated and signed tag for the latest commit. This tag will be used for the release. ```shell git tag -s v$VERSION -m "" ``` ```shell git show v$VERSION ``` -------------------------------- ### Interact with the App and Metrics Endpoint Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/examples/metrics-diff-port-uvicorn/README.md Shell commands to interact with the running FastAPI application and to fetch metrics from the separate Prometheus endpoint. ```shell curl localhost:8000/ping ``` ```shell curl localhost:9000/metrics ``` -------------------------------- ### Push Release Tag Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/RELEASE.md Push the newly created tag to the remote repository. This action typically triggers the release workflow. ```shell git push origin v$VERSION ``` -------------------------------- ### Update Version in __init__.py Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/RELEASE.md Update the __version__ variable in the package's __init__.py file to the new release version. This command uses sed to find and replace the line containing __version__. ```shell sed -i "/^__version__/c\__version__ = \"$VERSION\"" src/*/__init__.py ``` ```shell grep -n -H __version__ src/*/__init__.py ``` -------------------------------- ### Import Instrumentator Class Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/README.md Import the Instrumentator class from the library. This is the first step to instrumenting your FastAPI application. ```python from prometheus_fastapi_instrumentator import Instrumentator ``` -------------------------------- ### Interact with the FastAPI App Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/examples/default-metrics-diff-labels/README.md Use curl to interact with the running FastAPI application. Access the '/ping' endpoint for a basic check and '/metrics' to view Prometheus metrics. ```shell curl localhost:8000/ping ``` ```shell curl localhost:8000/metrics ``` -------------------------------- ### View Git Log Graph Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/RELEASE.md Display a graphical representation of the recent commit history to ensure the tree structure is as expected. ```shell git log --graph --oneline --all -n 5 ``` -------------------------------- ### Update Pre-Commit Hooks Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/devel/pre-commit.md Automatically update all pre-commit hooks to their latest versions. Run this command periodically to ensure hooks are up-to-date. ```bash pre-commit autoupdate ``` -------------------------------- ### Create Custom HTTP Requested Languages Metric Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/README.md Defines and returns a custom instrumentation function to count the occurrences of requested languages based on the 'Accept-Language' header. This function requires careful handling of the request and response objects within the 'Info' object. ```python from typing import Callable from prometheus_fastapi_instrumentator.metrics import Info from prometheus_client import Counter def http_requested_languages_total() -> Callable[[Info], None]: METRIC = Counter( "http_requested_languages_total", "Number of times a certain language has been requested.", labelnames=("langs",) ) def instrumentation(info: Info) -> None: langs = set() lang_str = info.request.headers["Accept-Language"] for element in lang_str.split(","): element = element.split(";")[0].strip().lower() langs.add(element) for language in langs: METRIC.labels(language).inc() return instrumentation ``` -------------------------------- ### Add Latency Metric with Custom Buckets Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/README.md Adds the default latency metric to the instrumentator, allowing for custom bucket configurations. ```python instrumentator.add(metrics.latency(buckets=(1, 2, 3,))) ``` -------------------------------- ### Specify Static Custom Labels Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/README.md Add static custom labels to metrics by passing them to the metrics closure. Useful for filtering or categorizing metrics. ```python Instrumentator().add( metrics.default( custom_labels={"environment": "dev"}, ), ).instrument(app).expose(app) ``` -------------------------------- ### Add Custom Metric to Instrumentator Source: https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/master/README.md Registers a custom instrumentation function, such as the http_requested_languages_total metric, with the instrumentator instance. ```python instrumentator.add(http_requested_languages_total()) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.