From 59b345294cda9cf25b20ae7bfd617f62655ad6da Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Thu, 27 Jun 2024 16:37:41 -0500 Subject: Fix bug with the logging setup. --- scripts/qcapp_wsgi.py | 48 +++++++++++++++++++++++++++--------------------- 1 file changed, 27 insertions(+), 21 deletions(-) diff --git a/scripts/qcapp_wsgi.py b/scripts/qcapp_wsgi.py index 9fb63cb..349c006 100644 --- a/scripts/qcapp_wsgi.py +++ b/scripts/qcapp_wsgi.py @@ -1,4 +1,5 @@ """Run the application""" +import os import sys from logging import getLogger, StreamHandler @@ -7,6 +8,30 @@ from flask import Flask from qc_app import create_app from qc_app.check_connections import check_db, check_redis +def setup_logging(appl: Flask) -> Flask: + """Setup appropriate logging paradigm depending on environment.""" + # https://datatracker.ietf.org/doc/html/draft-coar-cgi-v11-03#section-4.1.17 + # https://wsgi.readthedocs.io/en/latest/proposals-2.0.html#making-some-keys-required + # https://peps.python.org/pep-3333/#id4 + software, *_version_and_comments = os.environ.get( + "SERVER_SOFTWARE", "").split('/') + if bool(software): + gunicorn_logger = getLogger("gunicorn.error") + appl.logger.handlers = gunicorn_logger.handlers + appl.logger.setLevel(gunicorn_logger.level)#pylint: disable=[no-member] + else: + loglevel = appl.config["LOG_LEVEL"].upper() + # Maybe call `logging.dictConfig(…)` here instead of all this stuff below + handler_stderr = StreamHandler(stream=sys.stderr) + appl.logger.addHandler(handler_stderr) + rootlogger = getLogger() + rootlogger.addHandler(handler_stderr) + rootlogger.setLevel(loglevel) + appl.logger.setLevel(loglevel) + + return appl + + def check_and_build_app() -> Flask: """Setup the application for running.""" # Setup the app @@ -15,30 +40,11 @@ def check_and_build_app() -> Flask: # Check connections check_db(appl.config["SQL_URI"]) check_redis(appl.config["REDIS_URL"]) - return appl + return setup_logging(appl) -def setup_logging(appl: Flask): - """Setup application logging""" - loglevel = appl.config["LOG_LEVEL"].upper() - - # Maybe call `logging.dictConfig(…)` here instead of all this stuff below - handler_stderr = StreamHandler(stream=sys.stderr) - appl.logger.addHandler(handler_stderr) - - rootlogger = getLogger() - rootlogger.addHandler(handler_stderr) - rootlogger.setLevel(loglevel) - - appl.logger.setLevel(loglevel) app = check_and_build_app() -if __name__ != "__main__":# Running via gunicorn - gunicorn_logger = getLogger("gunicorn.error") - app.logger.handlers = gunicorn_logger.handlers - app.logger.setLevel(gunicorn_logger.level)#pylint: disable=[no-member] - -if __name__ == "__main__":# Running via flask +if __name__ == "__main__": # Run the app - setup_logging(app) app.run() -- cgit v1.2.3