Configure Logging in gunicorn based application in docker container

Carvia Tech | April 26, 2020 | 2 min read | 31 views


In this tutorial you will learn how to add logging in flask application running on gunicorn server in docker

Flask Based application

Library : logging

We will be using logging library to enable logs

from flask import Response
import json
import logging

We will add configuration for logging now and set at app application level

app = Flask(__name__)

gunicorn_logger = logging.getLogger('gunicorn.error')
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)

Now we can add various types of logs in our application. Let’s add info in health check endpoint

@app.route("/health", methods=['GET'])
def get_status():
    app.logger.info("checking health of application")
    return Response(json.dumps({"status":"UP"}), status=200, mimetype='application/json')

We can add debug logs for adding logging for IP address from which application is receiving request

@app.route("/get_ip", methods=["GET"])
def get_ip():
    app.logger.debug("Incoming request from IP: %s", request.remote_addr)
    app.logger.debug("Incoming request from IP: %s", request.HTTP_X_FORWARDED_FOR) # Incase of nginx
    return Response(json.dumps({'ip': request.remote_addr}), status=200, mimetype='application/json')

Flask Blueprints based application

Now, let’s say if we are using blueprints and want to configure logging there. Above configuration won’t work for blueprints. For that, we will need to use current_app and localproxy

from flask import Response, current_app
import json
import logging

We will add configuration for logging now and set at app application level

app = Flask(__name__)

logger = LocalProxy(lambda: current_app.logger)

Now we can add various types of logs in our application. Let’s add info in health check endpoint

@app.route("/health", methods=['GET'])
def get_status():
    logger.info("checking health of application")
    return Response(json.dumps({"status":"UP"}), status=200, mimetype='application/json')

Top articles in this category:
  1. Python Flask Interview Questions
  2. Google Data Scientist interview questions with answers
  3. Top 100 interview questions on Data Science & Machine Learning
  4. Python coding challenges for interviews
  5. Part 3: Dockerize Flask application and build CI/CD pipeline in Jenkins
  6. Part 2: Deploy Flask API in production using WSGI gunicorn with nginx reverse proxy
  7. Deploying Keras Model in Production with TensorFlow 2.0


Find more on this topic:
Machine Learning image
Machine Learning

Data science, machine learning, python, R, big data, spark, the Jupyter notebook, and much more

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info