From 300d844a60f84e4afc85f15790b8902742f242ef Mon Sep 17 00:00:00 2001 From: Benjamin Dauvergne Date: Thu, 15 Oct 2020 10:30:20 +0200 Subject: [PATCH] misc: disable logging in runscript and shell when in command shell (#47708) Command shell context is guessed by the presence of the TERM environment variable (should not happen when launched by crond, initd or systemd). --- .../management/commands/__init__.py | 21 +++++++++++++++++++ .../management/commands/runscript.py | 5 ++++- hobo/multitenant/management/commands/shell.py | 6 +++++- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/hobo/multitenant/management/commands/__init__.py b/hobo/multitenant/management/commands/__init__.py index 168c765..5d6b70d 100644 --- a/hobo/multitenant/management/commands/__init__.py +++ b/hobo/multitenant/management/commands/__init__.py @@ -173,3 +173,24 @@ class SyncCommon(BaseCommand): def _notice(self, output): if int(self.options.get('verbosity', 1)) >= 1: self.stdout.write(self.style.NOTICE(output)) + + +def disable_global_logging(): + import os + import logging + import sys + + if 'TERM' not in os.environ: + return + + # try to disable sentry + if 'sentry_sdk' in sys.modules: + import sentry_sdk + sentry_sdk.init() + + # then try to disable journald, syslog logging and mail admins + root_logger = logging.getLogger() + for handler in list(root_logger.handlers): + hdlr_class_name = handler.__class__.__name__ + if hdlr_class_name in ['JournalHandler', 'SysLogHandler', 'AdminEmailHandler']: + root_logger.handlers.remove(handler) diff --git a/hobo/multitenant/management/commands/runscript.py b/hobo/multitenant/management/commands/runscript.py index e3fd396..6506f86 100644 --- a/hobo/multitenant/management/commands/runscript.py +++ b/hobo/multitenant/management/commands/runscript.py @@ -21,12 +21,15 @@ import sys from django.core.management.base import BaseCommand -class Command(BaseCommand): +from . import disable_logging + +class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs=argparse.REMAINDER) def handle(self, *args, **options): + disable_global_logging() fullpath = os.path.dirname(os.path.abspath(args[0])) sys.path.insert(0, fullpath) module_name = os.path.splitext(os.path.basename(args[0]))[0] diff --git a/hobo/multitenant/management/commands/shell.py b/hobo/multitenant/management/commands/shell.py index 08bceb3..7ae6923 100644 --- a/hobo/multitenant/management/commands/shell.py +++ b/hobo/multitenant/management/commands/shell.py @@ -1,6 +1,10 @@ -from hobo.multitenant.management.commands import TenantWrappedCommand +from hobo.multitenant.management.commands import TenantWrappedCommand, disable_global_logging from django.core.management.commands import shell class Command(TenantWrappedCommand): COMMAND = shell.Command + + def handle(self, *args, **kwargs): + disable_global_logging() + super(Command, self).handle(*args, **kwargs) -- 2.28.0