How to log to StatsD using FastAPI and Gunicorn

173 Views Asked by At

I have a FastAPI that I am serving up using gunicorn. I am trying to send statistics to a DataDog agent on localhost that's running StatsD (DogStatsD) using the statsd_host argument described in the docs.

gunicorn \
  -b "0.0.0.0:8080" \
  -w 4 \
  -k unicorn.workers.UvicornWorker \
  --name my_app \
  --statsd_host "localhost:8125" \
  --dogstatsd-tags "app:my_app" \
  foo.bar:my_app

I can see using lsof that gunicorn is creating a socket connection to my Datadog agent at localhost:8125. I can also write metrics manually to DogStatsD using netcat (echo 'foo:1|c" | nc -u localhost 8125), so I know that the DataDog agent is correctly set up.

The problem is that no metrics are shipped to DataDog. It appears that the UvicornWorker is broken and doesn't ship metrics: uvicorn#610.

Gunicorn should ship lots of metrics to Datadog (https://docs.datadoghq.com/integrations/gunicorn/), including details of request rates, response statuses etc. My question is how do I ship metrics from FastAPI to Datadog using DogStatsd if I am running through gunicorn? Is there another production-grade way of running FastAPI instead of gunicorn such that I can easily ship metrics to DataDog?

1

There are 1 best solutions below

0
TanThien On

--statsd_host isn't have arg in gunicorn run without file config. It should --statsd-host. Your right command is

gunicorn \
  -b "0.0.0.0:8080" \
  -w 4 \
  -k unicorn.workers.UvicornWorker \
  --name my_app \
  --statsd-host "localhost:8125" \
  --dogstatsd-tags "app:my_app" \
  foo.bar:my_app

If you want to use statsd_host you should pass it to a gunicorn.conf.py