Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update prometheus.py #3766

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 26 additions & 13 deletions prometheus.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import inspect
import logging
import uuid
import re

from fastapi import FastAPI, Request, Response
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint

EXCLUDED_USER_AGENTS = {'bot', 'spider', 'crawler', 'monitor', 'curl',
'wget', 'python-requests', 'kuma', 'health check'}

EXCLUDED_AGENT_PATTERN = re.compile("|".join(EXCLUDED_USER_AGENTS), re.IGNORECASE)

def start_monitor(app: FastAPI) -> None:
try:
Expand All @@ -20,19 +21,31 @@ def start_monitor(app: FastAPI) -> None:
['path', 'session', 'origin'])

class PrometheusMiddleware(BaseHTTPMiddleware):

async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
if 'id' not in request.session:
request.session['id'] = str(uuid.uuid4())
response = await call_next(request)
if response.headers.get('x-nicegui-content') == 'page':
agent = request.headers.get('user-agent', 'unknown').lower()
# ignore monitoring, web crawlers and the like
if not any(s in agent for s in EXCLUDED_USER_AGENTS):
origin_url = request.headers.get('referer', 'unknown')
visits.labels(request.get('path'), request.session['id'], origin_url).inc()
return response

try:
session_id = get_or_set_session_id(request)
response = await call_next(request)

if response.headers.get('x-nicegui-content') == 'page':
agent = request.headers.get('user-agent', 'unknown').lower()
# ignore monitoring, web crawlers, and bots
if not EXCLUDED_AGENT_PATTERN.search(agent):
origin_url = request.headers.get('referer', 'unknown')
visits.labels(request.url.path, session_id, origin_url).inc()
return response
except Exception as e:
logging.error(f"Error in PrometheusMiddleware: {str(e)}")
return await call_next(request)

def get_or_set_session_id(request: Request) -> str:
if 'id' not in request.session:
session_id = str(uuid.uuid4())
request.session['id'] = session_id
else:
session_id = request.session['id']
return session_id

# Only start Prometheus server in specific conditions (e.g., specific processes)
if inspect.stack()[-2].filename.endswith('spawn.py'):
prometheus_client.start_http_server(9062)

Expand Down