From a23eb674191572867d1161b2b43285e060781062 Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Thu, 12 Sep 2024 08:48:38 -0500 Subject: Gracefully print out debug messages even outside app context The flask.current_app object depends on the application context existing. In the case that no such context existing, then we still log out information, gracefully with this commit. --- gn3/commands.py | 4 +++- gn3/debug.py | 12 +++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/gn3/commands.py b/gn3/commands.py index 7a9ba67..d5215f8 100644 --- a/gn3/commands.py +++ b/gn3/commands.py @@ -3,6 +3,7 @@ commands""" import sys import json import pickle +import logging import tempfile import subprocess @@ -161,7 +162,8 @@ def run_cmd(cmd: str, success_codes: Tuple = (0,), env: Optional[str] = None) -> out = str(results.stdout, 'utf-8') if results.returncode not in success_codes: # Error! out = str(results.stderr, 'utf-8') - current_app.logger.debug(out) + (# We do not always run this within an app context + current_app.logger.debug if current_app else logging.debug)(out) return {"code": results.returncode, "output": out} def run_async_cmd( diff --git a/gn3/debug.py b/gn3/debug.py index acc2402..3c88bd3 100644 --- a/gn3/debug.py +++ b/gn3/debug.py @@ -2,11 +2,17 @@ import logging from flask import current_app -logger = logging.getLogger(__name__) +__this_module_name__ == __name__ + +def getLogger(): + return ( + logging.getLogger(__name__) + if not bool(current_app) + else current_app.logger) def __pk__(*args): value = args[-1] title_vals = " => ".join(args[0:-1]) - current_app.logger.setLevel(logging.DEBUG) # Force debug level since we assume we are using it! - current_app.logger.debug("%s: %s", title_vals, value) + logger = getLogger() + logger.debug("%s: %s", title_vals, value) return value -- cgit v1.2.3