Skip to main content

Middleware for tracking ASGI requests with Matomo

Project description

asgi-matomo

PyPI version PyPI - Python Version PyPI - Downloads Docs MIT License

Maturity badge - level 3 Stage

Code Coverage

CI(check) CI(release) CI(rolling) CI(test)

Tracking requests with Matomo from ASGI apps.

MatomoMiddleware adds tracking of all requests to Matomo to ASGI applications (Starlette, FastAPI, Quart, etc.). The intended usage is for api tracking (backends).

Note If you serve HTML (directly or by templates), it is suggested to track those parts through Matomo's javascript tracking.

Installation

pip install asgi-matomo

What is tracked

Currently this middleware tracks:

  • url
  • ua: user_agent
  • gt_ms: mesaured as the time before and after this middleware call next in the asgi stack.
  • send_image=0 for performance issues
  • cvar with at least http_status_code and http_method set.
  • lang if accept-lang is set
  • cip client ip, requires access_token to be given.
  • action_name that defaults to path, but can be specified.

You can also pass variable to track by adding an asgi_matomo dict in the state dict of the ASGI scope:

scope = {
  "state": {
    "asgi_matomo": {
      "e_a": "Playing",
      "cvar": {
        "your": "custom",
        "data": "here",
      }
    }
  }
}

The keys of the asgi_matomo dict is expected to be valid parameter for the Matomo HTTP Tracking API. cvar is serialized with the standard json lib.

You can also track time spent on different tasks with trackers.PerfMsTracker.

import asyncio
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.middleware import Middleware

from asgi_matomo import MatomoMiddleware
from asgi_matomo.trackers import PerfMsTracker

async def homepage(request):
    async with PerfMsTracker(scope=request.scope, key="pf_srv"):
        # fetch/compute data
        await asyncio.sleep(1)
        data = {"data": "a"*4000}
    return JSONResponse(data)

app = Starlette(
  routes=[Route("/", homepage)],
  middleware=[
    Middleware(
      MatomoMiddleware,
      matomo_url="YOUR MATOMO TRACKING URL",
      idsite=12345, # your service tracking id
  )],
)

Examples

Starlette

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.middleware import Middleware

from asgi_matomo import MatomoMiddleware

async def homepage(request):
    return JSONResponse({"data": "a" * 4000})

app = Starlette(
  routes=[Route("/", homepage)],
  middleware=[
    Middleware(
      MatomoMiddleware,
      matomo_url="YOUR MATOMO TRACKING URL",
      idsite=12345, # your service tracking id
  )],
)

FastAPI

from fastapi import FastAPI
from asgi_matomo import MatomoMiddleware

app = FastAPI()
app.add_middleware(
  MatomoMiddleware,
  matomo_url="YOUR MATOMO TRACKING URL",
  idsite=12345, # your service tracking id
)

@app.get("/")
def home() -> dict:
    return {"data": "a" * 4000}

API Reference

Overview

app.add_middleware(
  MatomoMiddleware,
  matomo_url="YOUR MATOMO TRACKING URL",
  idsite=12345, # your service tracking id
  access_token="SECRETTOKEN",
  assume_https=True,
  exclude_paths=["/health"],
  exclude_patterns=[".*/old.*"],
  route_details={
    "route": {
      "action_name": "Name",
    }
  }
  client=None,
  http_timeout=5,
  allowed_methods="all-methods",
  ignored_methods=None
)

Parameters:

  • (Required) matomo_url: The URL to make your tracking calls to.
  • (Required) idsite: The tracking id for your service.
  • (Optional) access_token: Access token for Matomo. If this is set cip is also tracked. Required for tracking some data.
  • (Optional) assume_https: If True, set tracked url scheme to https, useful when running behind a proxy. Defaults to True.
  • (Optional) exclude_paths: A list of paths to exclude, only excludes path that is equal to a path in this list. These are tried before exclude_patterns. Defaults to None.
  • (Optional) exclude_patterns: A list of regex patterns that are compiled, and then exclude a path from tracking if any pattern match. Defaults to None. These are tried after exclude_paths.
  • (Optional) route_details: A dict with custom route-specific tracking data. Defaults to None.
  • (Optional) client: A custom http client to use (must use the same API as httpx.Client). Defaults to None, a client is created.
  • (Optional) http_timeout: Timeout to use for the client being created. Ignored if a custom client is provided. Defaults to 5.
  • (Optional) allowed_methods: List of HTTP methods that should be tracked. Defaults to "all-methods".
  • (Optional) ignored_methods: List of HTTP methods to ignored. Ignored methods takes precedence over allowed methods. Defaults to None.

Notes:

Ideas for further work

  • filtering tracked of urls
  • custom extraction of tracked data

This project keeps a changelog.

Development

This project uses uv and pre-commit.

Download files

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

Source Distribution

asgi_matomo-0.6.2.tar.gz (7.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

asgi_matomo-0.6.2-py3-none-any.whl (8.5 kB view details)

Uploaded Python 3

File details

Details for the file asgi_matomo-0.6.2.tar.gz.

File metadata

  • Download URL: asgi_matomo-0.6.2.tar.gz
  • Upload date:
  • Size: 7.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for asgi_matomo-0.6.2.tar.gz
Algorithm Hash digest
SHA256 a3aa46ba3dfae92d195826179428d794422c137504d847199012a1f297aaebaf
MD5 093696d77780c5df62cbf59b4a12ea76
BLAKE2b-256 5f4e7c4e01589e520bbf08e5aa3395758e38f630b6c121c1139987ff68768c00

See more details on using hashes here.

Provenance

The following attestation bundles were made for asgi_matomo-0.6.2.tar.gz:

Publisher: release.yml on spraakbanken/asgi-matomo

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file asgi_matomo-0.6.2-py3-none-any.whl.

File metadata

  • Download URL: asgi_matomo-0.6.2-py3-none-any.whl
  • Upload date:
  • Size: 8.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for asgi_matomo-0.6.2-py3-none-any.whl
Algorithm Hash digest
SHA256 84ff688a416a9ce4bc5e832fe628634f5b2d269b9e77e72f971147f297a2d24c
MD5 728854009c156da6ec45d274152d8903
BLAKE2b-256 c8dffb0ae3dd9d76f856707ab8f2a53ffb95731a0f93e0e97b41a5e0607587ea

See more details on using hashes here.

Provenance

The following attestation bundles were made for asgi_matomo-0.6.2-py3-none-any.whl:

Publisher: release.yml on spraakbanken/asgi-matomo

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

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