Search code examples
pythonflaskloggingpython-logging

Simple log filtering with Flask


I'm new to Flask and I'm having trouble filtering out some logs. My use case is simple: I don't want to log health check queries, which hit the route /health.

Here's what I have:

from flask import Flask
from flask.logging import logging

class NoHealth(logging.Filter):
    def filter(self, record):
        return 'GET /health' not in record.getMessage()

no_health = NoHealth()
app = Flask(__name__)
app.logger.addFilter(no_health)
app.logger.setLevel('INFO')

@app.route('/health')
def health_check():
    return "OK"

The logs I want to drop look like this:

127.0.0.1 - - [31/Mar/2020 17:51:03] "GET /health HTTP/1.1" 200 -

They're still coming through, however. What am I missing?


Solution

  • Access logs are written by werzeug (web server running flask app in this case). So, better option would be to increase logging level to warning:

    logging.getLogger("werkzeug").setLevel('WARNING')
    

    In case you really want to use custom filter NoHealth, you can go with following solution:

    logging.getLogger("werkzeug").addFilter(NoHealth())