[PYTHON] Customize Flask access logs

Thing you want to do

Create the following Flask (version 1.1.2) program

from flask import Flask

app = Flask(__name__)


@app.route("/")
def hello():
    return "Hello World!"


if __name__ == "__main__":
    app.run(host='0.0.0.0')

When I run it and access it, the following log appears,

127.0.0.1 - - [14/Apr/2020 19:13:43] "\x1b[37mGET / HTTP/1.1\x1b[0m" 200 -

This access log is awkward because it contains unnecessary strings (for me) and the body message is colored.

So I'll show you how to customize this log.

How to customize

In conclusion, since Flask's internal logger named Werkzeug (version 1.0.1) outputs the above log, we will get and customize Werkzeug's logger as follows.

Example 1) Change the log level to ERROR

from flask import Flask
import logging

#Get a logger
werkzeug_logger = logging.getLogger("werkzeug")
#Level change
werkzeug_logger.setLevel(logging.ERROR)

app = Flask(__name__)


@app.route("/")
def hello():
    return "Hello World!"


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=4001)

Example 2) Change the output character string

By default, it is output in the format of (IP address) --- [(date and time)](message (colored)), but in the following example, the part of (message) is output without color.

from flask import Flask
import logging
from werkzeug.serving import WSGIRequestHandler
from werkzeug.urls import uri_to_iri

werkzeug_logger = logging.getLogger("werkzeug")


def custom_log_request(self, code="-", size="-"):
    try:
        path = uri_to_iri(self.path)
        msg = "%s %s %s" % (self.command, path, self.request_version)
    except AttributeError:
        msg = self.requestline
    code = str(code)
    werkzeug_logger.info('"%s" %s %s' % (msg, code, size))


#Function replacement
WSGIRequestHandler.log_request = custom_log_request

app = Flask(__name__)


@app.route("/")
def hello():
    return "Hello World!"


if __name__ == "__main__":
    app.run(host='0.0.0.0')

The output log is simple with no color as shown below

"GET / HTTP/1.1" 200 -

Why is this method good?

Flask uses a package called werkzeug internally.

That's why Flask has two loggers. One is the logger used by Flask, which can be obtained with logging.getLogger ("app.flask "). The other is the logger used by werkzeug, which can be obtained with logging.getLogger ("werkzeug") .

The above log is output at the location of ↓ in the werkzeug source code.

https://github.com/pallets/werkzeug/blob/1.0.x/src/werkzeug/serving.py#L406

So by replacing this function, you can customize it.

Even if I messed with the logger of ʻapp.flask`, this log does not disappear, so I was really into it (laugh)

Recommended Posts

Customize Flask access logs
Merge Apache access logs
flask
flask