search

Thursday, February 18, 2016

Set up logging with Flask and gunicorn

Let's say that we want to be able to log in the specified log file and syslog. Our application - is a simple app.py file. The first step, I suggest, is to set logger name:
import os

from flask import Flask


app = Flask(__name__)
app.logger_name = "flask.app"

# ...

if __name__ == "__main__":
    app.run()
You can log in your project like this:
app.logger.info("Hello")
A log configuration file for the gunicorn may look something like this:
[loggers]
keys=root, gunicorn.error, gunicorn.access, requests.packages.urllib3.connectionpool, __main__

[handlers]
keys=log_file, syslog

[formatters]
keys=generic

[logger_root]
level=INFO
handlers=log_file, syslog

[logger___main__]
level=DEBUG
handlers=log_file, syslog
propagate=0
qualname=__main__

[logger_gunicorn.error]
level=INFO
handlers=log_file, syslog
propagate=0
qualname=gunicorn.error

[logger_gunicorn.access]
level=INFO
handlers=log_file, syslog
propagate=0
qualname=gunicorn.access

[logger_requests.packages.urllib3.connectionpool]
level=WARN
handlers=log_file, syslog
propagate=0
qualname=requests.packages.urllib3.connectionpool

[handler_syslog]
class=logging.handlers.SysLogHandler
formatter=generic
args=()

[handler_log_file]
class=logging.FileHandler
formatter=generic
args=('/home/myuser/log/gunicorn.log',)

[formatter_generic]
format=%(asctime)s [%(process)d:%(name)s:%(lineno)s] [%(levelname)s] %(message)s
datefmt=%Y-%m-%d %H:%M:%S
class=logging.Formatter
The last step is starting gunicorn:
gunicorn app:app --log-config /home/myuser/gunicorn_logging.conf

No comments:

Post a Comment