Python Flask Microservice: Monitoring with Prometheus and Grafana
About Monitoring with Prometheus and Grafana
Both Prometheus and Grafana are compatible with microservice applications, integrating Prometheus with Flask is straightforward to provide performance and monitoring metrics.
Here I will update the docker-compose to add Prometheus and Grafana as services, then add Prometheus metrics in both order and user application code by importing PrometheusMetrics from the prometheus_flask_exporter module, which is used to expose Prometheus metrics for the Flask application. then initialize Prometheus metrics with metrics = PrometheusMetrics(app). Use @metrics.counter('get_orders_count', 'Count of calls to the get_orders endpoint') to define a Prometheus counter metric that increments each time the get_orders endpoint is called.
Import os to enable environment variable for Logstash host, logstash_host = os.getenv('LOGSTASH_HOST', 'localhost') to fetche the Logstash host from environment variables, defaulting to localhost.
Now Run docker-compose to bring all containers up and running. Should see all services with Prometheus and Grafana.
Verify Prometheus and Grafana
Access Grafana via http://localhost:3000, log in with admin/admin.
Add Prometheus as a Data Source in Grafana by setting the URL to http://localhost:9090 and save.
Create Dashboards in Grafana to use the Prometheus data source to visualize metrics from user-service and order-service.
Conclusion
Now we can enable monitoring with Prometheus and Grafana.
In the next post, I will see how to depoly our Python Flask microservice into Kubernetes.