Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Display access logs in Docker logs, sync Flask log level with Gunicorn's #274

Merged
merged 1 commit into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions scripts/gunicorn.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ set -euo pipefail

gunicorn \
"usaon_benefit_tool:create_app()" \
--log-level="info" \
--access-logfile=- \
--bind="0.0.0.0:5000" \
--workers="${NUM_WORKERS:-5}" \
--certfile="/run/secrets/site.crt" --keyfile="/run/secrets/site.key"
35 changes: 35 additions & 0 deletions usaon_benefit_tool/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
import os
import time
from typing import Final
Expand All @@ -6,6 +7,7 @@
from flask_bootstrap import Bootstrap5
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from loguru import logger as loguru_logger
from markdown import Markdown
from markupsafe import Markup
from sqlalchemy import MetaData
Expand Down Expand Up @@ -43,6 +45,7 @@ def create_app():
_monkeypatch()

app = Flask(__name__)
_setup_logging(app)
_setup_config(app)
_setup_proxy_support(app)

Expand All @@ -58,6 +61,30 @@ def create_app():
return app


def _setup_logging(app) -> None:
"""Route logs from loguru to the app logger, and respect Gunicorn log-level.

Based on: https://gist.github.com/M0r13n/0b8c62c603fdbc98361062bd9ebe8153
"""
if "gunicorn" in os.environ.get("SERVER_SOFTWARE", ""):
# sync the application log level with Gunicorn's log level
gunicorn_logger = logging.getLogger('gunicorn.error')
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)
loguru_logger.info(
f"Detected Gunicorn server and set log level to {gunicorn_logger.level}.",
)

class InterceptHandler(logging.Handler):
def emit(self, record):
logger_opt = loguru_logger.opt(depth=6, exception=record.exc_info)
logger_opt.log(record.levelno, record.getMessage())

app.logger.addHandler(InterceptHandler())

loguru_logger.info("Logging configured.")


def _setup_config(app) -> None:
app.config['SECRET_KEY'] = os.environ.get('FLASK_SECRET_KEY', 'youcanneverguess')
app.config['SQLALCHEMY_DATABASE_URI'] = db_connstr(app)
Expand All @@ -71,6 +98,8 @@ def _setup_config(app) -> None:
# DEV ONLY: Disable login
app.config['LOGIN_DISABLED'] = envvar_is_true("USAON_BENEFIT_TOOL_LOGIN_DISABLED")

loguru_logger.info("App configuration initialized.")


def _setup_proxy_support(app) -> None:
if envvar_is_true("USAON_BENEFIT_TOOL_PROXY"):
Expand Down Expand Up @@ -105,6 +134,8 @@ def before_request():
if time.time() >= token['expires_at']:
del s['google_oauth_token']

loguru_logger.info("Login configured.")


def _register_template_helpers(app) -> None:
# TODO: Consider context processors instead?
Expand All @@ -127,6 +158,8 @@ def _register_template_helpers(app) -> None:
dateformat=lambda date: date.strftime("%Y-%m-%d %H:%M%Z"),
)

loguru_logger.info("Template helpers registered.")


def _register_blueprints(app) -> None:
# TODO: Extract function register_blueprints
Expand Down Expand Up @@ -154,6 +187,8 @@ def _register_blueprints(app) -> None:
app.register_blueprint(nodes_bp)
app.register_blueprint(node_bp)

loguru_logger.info("Blueprints registered.")


def _monkeypatch():
import wtforms_sqlalchemy
Expand Down
Loading