Custom Metrics
NotesWe now have the application publishing metrics, but it’s also useful to add our own: for example, how many times the home page has been viewed.
The prometheus-client package does this. It’s installed along with prometheus-fastapi-instrumentator, so there’s nothing new to install.
Create a counter in home_view.py, and increase it each time the page is viewed:
from prometheus_client import Counter # NEWHOME_PAGE_HITS = Counter('home_page_hits', 'Number of times the home page has been viewed') # NEW@router.get('/', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def home_view(*, request: Request, session: Session = Depends(get_session_db)):
HOME_PAGE_HITS.inc() # NEW
blogposts = get_blogposts_api(limit=3, session=session)
current_user = is_user(request, session)The counter is created once, when the module is imported, and inc() adds one each time.
Restart the application, and you’ll see the counter at http://localhost:8000/metrics:
# HELP home_page_hits_total Number of times the home page has been viewed
# TYPE home_page_hits_total counter
home_page_hits_total 3.0Prometheus adds _total to the name of every counter. Refresh the home page in a browser and see it increase.
A Counter only ever goes up (it resets to zero when the application restarts), which is right for counting events. Prometheus has functions designed for counters, such as rate() and increase(), which work out how fast it’s going up, and cope with the resets. (An earlier version of this guide used a Gauge, which is for values that go up and down, such as the number of users online.)
Prometheus is already scraping the application, so the new metric is there too. Try it in the Prometheus web interface, under Query, for example:
increase(home_page_hits_total[5m])That’s how many times the home page was viewed in the last five minutes.