Skip to content

Commit

Permalink
feat: add logfire instrumentations for fastapi backend
Browse files Browse the repository at this point in the history
  • Loading branch information
vichannnnn committed Oct 17, 2024
1 parent 6c482d2 commit 9a7309d
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 39 deletions.
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ services:
MAILTRAP_BEARER_TOKEN: ${MAILTRAP_BEARER_TOKEN}
MAILTRAP_API_KEY: ${MAILTRAP_API_KEY}
PRODUCTION: ${PRODUCTION}
LOGFIRE_TOKEN: ${LOGFIRE_TOKEN}
restart: unless-stopped
volumes:
- ./holy-grail-backend/backend:/app
Expand Down
2 changes: 1 addition & 1 deletion holy-grail-backend/backend/app/api/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
api_router.include_router(analytics.router, tags=["Analytics"], prefix="/analytics")
api_router.include_router(auth.router, tags=["Authentication"], prefix="/auth")
api_router.include_router(categories.router, tags=["Categories"])
api_router.include_router(dev.router, tags=["Dev"], prefix="/dev")
# api_router.include_router(dev.router, tags=["Dev"], prefix="/dev")
api_router.include_router(example.router, tags=["Example"])
api_router.include_router(library.router, tags=["Library"], prefix="/note")
api_router.include_router(library.notes_router, tags=["Library"], prefix="/notes")
Expand Down
68 changes: 34 additions & 34 deletions holy-grail-backend/backend/app/api/endpoints/dev.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
import re
from typing import List, Dict, Any, Optional
from fastapi import APIRouter
from app.api.deps import SessionDeveloper
from prometheus_client import generate_latest

router = APIRouter()


def parse_metric_line(line: str) -> Optional[Dict[str, Any]]:
"""Parse a single line of a metric."""
match = re.match(r"(\w+){?(.*)}?\s(.+)", line)
if match is not None:
metric_name, labels_str, value = match.groups()
labels = dict(re.findall(r'(\w+)="(.+?)"', labels_str))
return {"metric_name": metric_name, "labels": labels, "value": float(value)}
return None


def metrics_to_json(metrics_str: str) -> List[Dict[str, Any]]:
"""Convert all metrics to JSON."""

lines = metrics_str.split("\n")
metrics = [parse_metric_line(line) for line in lines]
metrics = [
metric for metric in metrics if metric is not None
] # Filter out any None values
return metrics


@router.get("/metrics")
async def expose_metrics(authenticated: SessionDeveloper): # pylint: disable=W0613
metrics_str = generate_latest().decode("utf8")
return metrics_to_json(metrics_str)
# import re
# from typing import List, Dict, Any, Optional
# from fastapi import APIRouter
# from app.api.deps import SessionDeveloper
# from prometheus_client import generate_latest
#
# router = APIRouter()
#
#
# def parse_metric_line(line: str) -> Optional[Dict[str, Any]]:
# """Parse a single line of a metric."""
# match = re.match(r"(\w+){?(.*)}?\s(.+)", line)
# if match is not None:
# metric_name, labels_str, value = match.groups()
# labels = dict(re.findall(r'(\w+)="(.+?)"', labels_str))
# return {"metric_name": metric_name, "labels": labels, "value": float(value)}
# return None
#
#
# def metrics_to_json(metrics_str: str) -> List[Dict[str, Any]]:
# """Convert all metrics to JSON."""
#
# lines = metrics_str.split("\n")
# metrics = [parse_metric_line(line) for line in lines]
# metrics = [
# metric for metric in metrics if metric is not None
# ] # Filter out any None values
# return metrics
#
#
# @router.get("/metrics")
# async def expose_metrics(authenticated: SessionDeveloper): # pylint: disable=W0613
# metrics_str = generate_latest().decode("utf8")
# return metrics_to_json(metrics_str)
7 changes: 4 additions & 3 deletions holy-grail-backend/backend/app/main.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import ast
import os

import logfire
from fastapi import FastAPI
from fastapi.middleware import cors
from prometheus_fastapi_instrumentator import Instrumentator

from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded

Expand Down Expand Up @@ -33,7 +33,8 @@
)

app.include_router(api_router)
Instrumentator().instrument(app)
logfire.configure()
logfire.instrument_fastapi(app)

# Force runs the google analytics and update scoreboard job once on app start up.

Expand Down
2 changes: 1 addition & 1 deletion holy-grail-backend/backend/app/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ PyJWT==2.7.0
slowapi
boto3==1.28.1
mailtrap
prometheus-fastapi-instrumentator==6.0.0
moto[s3]==4.2.13
requests-toolbelt==1.0.0
fpdf==1.7.2
pytz==2023.3.post1
logfire[fastapi]==1.1.0

# GOOGLE DEPENDENCIES
google-analytics-data==0.17.2
Expand Down

0 comments on commit 9a7309d

Please sign in to comment.