From ecefbf0c7665bad8e23e1891767512197c98348c Mon Sep 17 00:00:00 2001 From: Jason Held Date: Tue, 22 Aug 2023 15:55:44 -0400 Subject: [PATCH] support systemd journal logging --- diycrate/logging_config.py | 38 +++++++++++++++++++++++++++++++++++--- pyproject.toml | 1 + 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/diycrate/logging_config.py b/diycrate/logging_config.py index c8af554..8ca36cf 100644 --- a/diycrate/logging_config.py +++ b/diycrate/logging_config.py @@ -1,8 +1,17 @@ import os LOG_LEVEL = os.environ.get("DIY_CRATE_LOGGING_LEVEL") +LOG_TO_CONSOLE = os.environ.get("DIY_CRATE_LOGGING_CONSOLE") + if not LOG_LEVEL: LOG_LEVEL = "INFO" + +try: + from systemd import journal +except ImportError: + journal = None + + LOGGING = { "version": 1, "disable_existing_loggers": True, @@ -15,18 +24,41 @@ }, "handlers": { "console": { - "level": "DEBUG", + "level": LOG_LEVEL, "class": "logging.StreamHandler", "formatter": "verbose", } }, "loggers": { - "diycrate": {"handlers": ["console"], "propagate": True, "level": LOG_LEVEL}, + "diycrate": { + "handlers": ["console"], + "propagate": True, + "level": LOG_LEVEL, + }, "diycrate_app": { "handlers": ["console"], "propagate": True, "level": LOG_LEVEL, }, - "__main__": {"handlers": ["console"], "propagate": True, "level": LOG_LEVEL}, + "__main__": { + "handlers": ["console"], + "propagate": True, + "level": LOG_LEVEL, + }, }, } +# +if journal: + LOGGING["handlers"]["journal"] = { + "level": LOG_LEVEL, + "class": "systemd.journal.JournalHandler", + "formatter": "verbose", + } + + LOGGING["loggers"]["root"] = { + "handlers": ["journal"], + } + if not LOG_TO_CONSOLE: + LOGGING["loggers"]["diycrate_app"]["handlers"] = [] + LOGGING["loggers"]["__main__"]["handlers"] = [] + LOGGING["loggers"]["diycrate"]["handlers"] = [] diff --git a/pyproject.toml b/pyproject.toml index 2ed9e2f..5dfbd21 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,5 +48,6 @@ diycrate_server = "diycrate.server_app:main" [project.optional-dependencies] "dev" = ["ipython", "check-manifest", "black", "flake8", "pre-commit", "mypy"] +"systemd" = ["systemd-python"] "ci" = ["python-digitalocean"] "test" = ["tox", "check-manifest"]