Configure Logging in gunicorn based application in docker container

Upasana | April 26, 2020 | 2 min read | 537 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. Part 3: Dockerize Flask application and build CI/CD pipeline in Jenkins
  2. Part 2: Deploy Flask API in production using WSGI gunicorn with nginx reverse proxy
  3. Flask Interview Questions
  4. Top 100 interview questions on Data Science & Machine Learning
  5. Deploying Keras Model in Production with TensorFlow 2.0
  6. Creating custom Keras callbacks in python
  7. Machine Learning based Multiple choice questions

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.