From 28835fbca7fa248dd3d320436f45476c7b6234bb Mon Sep 17 00:00:00 2001 From: Jens Langhammer Date: Sat, 10 Sep 2022 13:24:31 +0200 Subject: [PATCH] root: re-use custom log helper from config and cleanup duplicate functions Signed-off-by: Jens Langhammer --- authentik/lib/config.py | 10 +++++----- authentik/root/settings.py | 19 +------------------ lifecycle/wait_for_db.py | 36 ++++++++++-------------------------- 3 files changed, 16 insertions(+), 49 deletions(-) diff --git a/authentik/lib/config.py b/authentik/lib/config.py index 6297c125c..0857d0bf4 100644 --- a/authentik/lib/config.py +++ b/authentik/lib/config.py @@ -62,7 +62,7 @@ class ConfigLoader: self.update_from_file(env_file) self.update_from_env() - def _log(self, level: str, message: str, **kwargs): + def log(self, level: str, message: str, **kwargs): """Custom Log method, we want to ensure ConfigLoader always logs JSON even when 'structlog' or 'logging' hasn't been configured yet.""" output = { @@ -95,7 +95,7 @@ class ConfigLoader: with open(url.path, "r", encoding="utf8") as _file: value = _file.read() except OSError as exc: - self._log("error", f"Failed to read config value from {url.path}: {exc}") + self.log("error", f"Failed to read config value from {url.path}: {exc}") value = url.query return value @@ -105,12 +105,12 @@ class ConfigLoader: with open(path, encoding="utf8") as file: try: self.update(self.__config, yaml.safe_load(file)) - self._log("debug", "Loaded config", file=path) + self.log("debug", "Loaded config", file=path) self.loaded_file.append(path) except yaml.YAMLError as exc: raise ImproperlyConfigured from exc except PermissionError as exc: - self._log( + self.log( "warning", "Permission denied while reading file", path=path, @@ -144,7 +144,7 @@ class ConfigLoader: current_obj[dot_parts[-1]] = value idx += 1 if idx > 0: - self._log("debug", "Loaded environment variables", count=idx) + self.log("debug", "Loaded environment variables", count=idx) self.update(self.__config, outer) @contextmanager diff --git a/authentik/root/settings.py b/authentik/root/settings.py index ebfc4713f..3b92967cb 100644 --- a/authentik/root/settings.py +++ b/authentik/root/settings.py @@ -3,10 +3,7 @@ import importlib import logging import os -import sys from hashlib import sha512 -from json import dumps -from time import time from urllib.parse import quote_plus import structlog @@ -20,20 +17,6 @@ from authentik.lib.sentry import sentry_init from authentik.lib.utils.reflection import get_env from authentik.stages.password import BACKEND_APP_PASSWORD, BACKEND_INBUILT, BACKEND_LDAP - -def j_print(event: str, log_level: str = "info", **kwargs): - """Print event in the same format as structlog with JSON. - Used before structlog is configured.""" - data = { - "event": event, - "level": log_level, - "logger": __name__, - "timestamp": time(), - } - data.update(**kwargs) - print(dumps(data), file=sys.stderr) - - LOGGER = structlog.get_logger() # Build paths inside the project like this: os.path.join(BASE_DIR, ...) @@ -484,4 +467,4 @@ if DEBUG: INSTALLED_APPS.append("authentik.core") -j_print("Booting authentik", version=__version__) +CONFIG.log("info", "Booting authentik", version=__version__) diff --git a/lifecycle/wait_for_db.py b/lifecycle/wait_for_db.py index 0b37480ed..2235b81cf 100755 --- a/lifecycle/wait_for_db.py +++ b/lifecycle/wait_for_db.py @@ -1,10 +1,8 @@ #!/usr/bin/env python """This file needs to be run from the root of the project to correctly import authentik. This is done by the dockerfile.""" -from json import dumps from sys import exit as sysexit -from sys import stderr -from time import sleep, time +from time import sleep from urllib.parse import quote_plus from psycopg2 import OperationalError, connect @@ -13,27 +11,13 @@ from redis.exceptions import RedisError from authentik.lib.config import CONFIG - -def j_print(event: str, log_level: str = "info", **kwargs): - """Print event in the same format as structlog with JSON. - Used before structlog is configured.""" - data = { - "event": event, - "level": log_level, - "logger": __name__, - "timestamp": time(), - } - data.update(**kwargs) - print(dumps(data), file=stderr) - - -j_print("Starting authentik bootstrap") +CONFIG.log("info", "Starting authentik bootstrap") # Sanity check, ensure SECRET_KEY is set before we even check for database connectivity if CONFIG.y("secret_key") is None or len(CONFIG.y("secret_key")) == 0: - j_print("----------------------------------------------------------------------") - j_print("Secret key missing, check https://goauthentik.io/docs/installation/.") - j_print("----------------------------------------------------------------------") + CONFIG.log("info", "----------------------------------------------------------------------") + CONFIG.log("info", "Secret key missing, check https://goauthentik.io/docs/installation/.") + CONFIG.log("info", "----------------------------------------------------------------------") sysexit(1) @@ -50,8 +34,8 @@ while True: break except OperationalError as exc: sleep(1) - j_print(f"PostgreSQL connection failed, retrying... ({exc})") - j_print("PostgreSQL connection successful") + CONFIG.log("info", f"PostgreSQL connection failed, retrying... ({exc})") + CONFIG.log("info", "PostgreSQL connection successful") REDIS_PROTOCOL_PREFIX = "redis://" if CONFIG.y_bool("redis.tls", False): @@ -68,7 +52,7 @@ while True: break except RedisError as exc: sleep(1) - j_print(f"Redis Connection failed, retrying... ({exc})", redis_url=REDIS_URL) - j_print("Redis Connection successful") + CONFIG.log("info", f"Redis Connection failed, retrying... ({exc})", redis_url=REDIS_URL) + CONFIG.log("info", "Redis Connection successful") -j_print("Finished authentik bootstrap") +CONFIG.log("info", "Finished authentik bootstrap")