Here's the Gunicorn config file:
import multiprocessing
certfile="domain.crt"
keyfile="server.key"
bind = "0.0.0.0:8443"
workers = multiprocessing.cpu_count() * 2 + 1
threads = 2
timeout = 300
graceful_timeout = 300
accesslog = "-"
errorlog = "-"
loglevel = "INFO"
As per Gunicorn documentation (https://docs.gunicorn.org/en/stable/settings.html#accesslog), if you set
- "accesslog" value as "-", then all gunicorn access logs will go to stdout.
- "errorlog" value as "-", then all gunicorn error logs will go to stderr.
Now, I want my application logs to be saved in the same place as gunicorn logs. Therefore, I want my application logs to go to stdout for now (because in gunicorn config, "accesslog" value is set as "-" which means stdout).
Here is the current application code:
from flask import Flask, jsonify
app = Flask(__name__)
if __name__ != '__main__':
gunicorn_logger = logging.getLogger('gunicorn.error')
logging.basicConfig(format=LOGGING_FORMAT, datefmt=DATE_FORMAT, level=gunicorn_logger.level)
@app.route('/')
def default_route():
"""Default route"""
app.logger.debug('this is a DEBUG message')
app.logger.info('this is an INFO message')
app.logger.warning('this is a WARNING message')
app.logger.error('this is an ERROR message')
app.logger.critical('this is a CRITICAL message')
return jsonify('hello world')
(Copied from https://trstringer.com/logging-flask-gunicorn-the-manageable-way/)
But here's the issue:
- All these application logs are redirected to stderr instead of stdout.
- I am only getting gunicorn access logs on stdout, although I should get the application logs as well.
How to solve this issue? What changes to make in the application code? There'a hacky fix which is working, but I am looking for better solutions. Hacky fix (Logging stdout to gunicorn access log?): In the application code, I can configure the logger as:
gunicorn_logger = logging.getLogger('gunicorn.error')
logging.basicConfig(format=LOGGING_FORMAT, datefmt=DATE_FORMAT, level=gunicorn_logger.level, stream=sys.stdout)
This seems to redirect my application logs to stdout, but this solution seems like hard coding the value of stream. I want it to be linked to gunicorn configuration, so that if in future I want to get all the logs into a file, I can just go and change it in gunicorn config file, instead of going in application code.