From c04a0cadef23c7ba57c90a50cf89ed6afbcaa019 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Otto=20Kek=C3=A4l=C3=A4inen?= Date: Mon, 4 Feb 2019 01:26:25 +0200 Subject: [PATCH] Extend common DebugLogger with option to log to stderr This makes it possible for e.g. command line tools to have the --debug option and when invoked print the existing debug messages directly to stderr so the user running the command can see them. --- utils/apparmor/common.py | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/utils/apparmor/common.py b/utils/apparmor/common.py index a06d4ba07..771543565 100644 --- a/utils/apparmor/common.py +++ b/utils/apparmor/common.py @@ -255,12 +255,20 @@ def type_is_str(var): else: return False + class DebugLogger(object): + '''Unified debug facility. Logs to file or stderr. + + Does not log anything by default. Will only log if environment variable + LOGPROF_DEBUG is set to a number between 1 and 3 or if method activateStderr + is run. + ''' def __init__(self, module_name=__name__): self.debugging = False - self.logfile = '/var/log/apparmor/logprof.log' self.debug_level = logging.DEBUG + if os.getenv('LOGPROF_DEBUG', False): + self.logfile = '/var/log/apparmor/logprof.log' self.debugging = os.getenv('LOGPROF_DEBUG') try: self.debugging = int(self.debugging) @@ -272,11 +280,11 @@ class DebugLogger(object): if self.debugging == 0: # debugging disabled, don't need to setup logging return if self.debugging == 1: - self.debug_level = logging.ERROR + self.debug_level = logging.ERROR # 40 elif self.debugging == 2: - self.debug_level = logging.INFO + self.debug_level = logging.INFO # 20 elif self.debugging == 3: - self.debug_level = logging.DEBUG + self.debug_level = logging.DEBUG # 10 try: logging.basicConfig(filename=self.logfile, level=self.debug_level, @@ -292,6 +300,15 @@ class DebugLogger(object): self.logger = logging.getLogger(module_name) + def activateStderr(self): + self.debugging = True + logging.basicConfig( + level=self.debug_level, + format='%(levelname)s: %(message)s', + stream=sys.stderr, + ) + self.logger = logging.getLogger(__name__) + def error(self, message): if self.debugging: self.logger.error(message)