More cleanup, yey!
[python_utils.git] / logging_utils.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 """Utilities related to logging."""
5
6 import collections
7 import contextlib
8 import datetime
9 import enum
10 import io
11 import logging
12 import os
13 import random
14 import sys
15 from logging.config import fileConfig
16 from logging.handlers import RotatingFileHandler, SysLogHandler
17 from typing import Any, Callable, Dict, Iterable, List, Optional
18
19 import pytz
20 from overrides import overrides
21
22 # This module is commonly used by others in here and should avoid
23 # taking any unnecessary dependencies back on them.
24 import argparse_utils
25 import config
26
27 cfg = config.add_commandline_args(f'Logging ({__file__})', 'Args related to logging')
28 cfg.add_argument(
29     '--logging_config_file',
30     type=argparse_utils.valid_filename,
31     default=None,
32     metavar='FILENAME',
33     help='Config file containing the logging setup, see: https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial',
34 )
35 cfg.add_argument(
36     '--logging_level',
37     type=str,
38     default='INFO',
39     choices=['NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
40     metavar='LEVEL',
41     help='The global default level below which to squelch log messages; see also --lmodule',
42 )
43 cfg.add_argument(
44     '--logging_format',
45     type=str,
46     default=None,
47     help='The format for lines logged via the logger module.  See: https://docs.python.org/3/library/logging.html#formatter-objects',
48 )
49 cfg.add_argument(
50     '--logging_date_format',
51     type=str,
52     default='%Y/%m/%dT%H:%M:%S.%f%z',
53     metavar='DATEFMT',
54     help='The format of any dates in --logging_format.',
55 )
56 cfg.add_argument(
57     '--logging_console',
58     action=argparse_utils.ActionNoYes,
59     default=True,
60     help='Should we log to the console (stderr)',
61 )
62 cfg.add_argument(
63     '--logging_filename',
64     type=str,
65     default=None,
66     metavar='FILENAME',
67     help='The filename of the logfile to write.',
68 )
69 cfg.add_argument(
70     '--logging_filename_maxsize',
71     type=int,
72     default=(1024 * 1024),
73     metavar='#BYTES',
74     help='The maximum size (in bytes) to write to the logging_filename.',
75 )
76 cfg.add_argument(
77     '--logging_filename_count',
78     type=int,
79     default=7,
80     metavar='COUNT',
81     help='The number of logging_filename copies to keep before deleting.',
82 )
83 cfg.add_argument(
84     '--logging_syslog',
85     action=argparse_utils.ActionNoYes,
86     default=False,
87     help='Should we log to localhost\'s syslog.',
88 )
89 cfg.add_argument(
90     '--logging_syslog_facility',
91     type=str,
92     default='USER',
93     choices=[
94         'NOTSET',
95         'AUTH',
96         'AUTH_PRIV',
97         'CRON',
98         'DAEMON',
99         'FTP',
100         'KERN',
101         'LPR',
102         'MAIL',
103         'NEWS',
104         'SYSLOG',
105         'USER',
106         'UUCP',
107         'LOCAL0',
108         'LOCAL1',
109         'LOCAL2',
110         'LOCAL3',
111         'LOCAL4',
112         'LOCAL5',
113         'LOCAL6',
114         'LOCAL7',
115     ],
116     metavar='SYSLOG_FACILITY_LIST',
117     help='The default syslog message facility identifier',
118 )
119 cfg.add_argument(
120     '--logging_debug_threads',
121     action=argparse_utils.ActionNoYes,
122     default=False,
123     help='Should we prepend pid/tid data to all log messages?',
124 )
125 cfg.add_argument(
126     '--logging_debug_modules',
127     action=argparse_utils.ActionNoYes,
128     default=False,
129     help='Should we prepend module/function data to all log messages?',
130 )
131 cfg.add_argument(
132     '--logging_info_is_print',
133     action=argparse_utils.ActionNoYes,
134     default=False,
135     help='logging.info also prints to stdout.',
136 )
137 cfg.add_argument(
138     '--logging_squelch_repeats',
139     action=argparse_utils.ActionNoYes,
140     default=True,
141     help='Do we allow code to indicate that it wants to squelch repeated logging messages or should we always log?',
142 )
143 cfg.add_argument(
144     '--logging_probabilistically',
145     action=argparse_utils.ActionNoYes,
146     default=True,
147     help='Do we allow probabilistic logging (for code that wants it) or should we always log?',
148 )
149 # See also: OutputMultiplexer
150 cfg.add_argument(
151     '--logging_captures_prints',
152     action=argparse_utils.ActionNoYes,
153     default=False,
154     help='When calling print, also log.info automatically.',
155 )
156 cfg.add_argument(
157     '--lmodule',
158     type=str,
159     metavar='<SCOPE>=<LEVEL>[,<SCOPE>=<LEVEL>...]',
160     help=(
161         'Allows per-scope logging levels which override the global level set with --logging-level.'
162         + 'Pass a space separated list of <scope>=<level> where <scope> is one of: module, '
163         + 'module:function, or :function and <level> is a logging level (e.g. INFO, DEBUG...)'
164     ),
165 )
166 cfg.add_argument(
167     '--logging_clear_preexisting_handlers',
168     action=argparse_utils.ActionNoYes,
169     default=True,
170     help=(
171         'Should logging code clear preexisting global logging handlers and thus insist that is '
172         + 'alone can add handlers.  Use this to work around annoying modules that insert global '
173         + 'handlers with formats and logging levels you might now want.  Caveat emptor, this may '
174         + 'cause you to miss logging messages.'
175     ),
176 )
177
178 BUILT_IN_PRINT = print
179 LOGGING_INITIALIZED = False
180
181
182 # A map from logging_callsite_id -> count of logged messages.
183 squelched_logging_counts: Dict[str, int] = {}
184
185
186 def squelch_repeated_log_messages(squelch_after_n_repeats: int) -> Callable:
187     """
188     A decorator that marks a function as interested in having the logging
189     messages that it produces be squelched (ignored) after it logs the
190     same message more than N times.
191
192     Note: this decorator affects *ALL* logging messages produced
193     within the decorated function.  That said, messages must be
194     identical in order to be squelched.  For example, if the same line
195     of code produces different messages (because of, e.g., a format
196     string), the messages are considered to be different.
197
198     """
199
200     def squelch_logging_wrapper(f: Callable):
201         import function_utils
202
203         identifier = function_utils.function_identifier(f)
204         squelched_logging_counts[identifier] = squelch_after_n_repeats
205         return f
206
207     return squelch_logging_wrapper
208
209
210 class SquelchRepeatedMessagesFilter(logging.Filter):
211     """
212     A filter that only logs messages from a given site with the same
213     (exact) message at the same logging level N times and ignores
214     subsequent attempts to log.
215
216     This filter only affects logging messages that repeat more than
217     a threshold number of times from functions that are tagged with
218     the @logging_utils.squelched_logging_ok decorator; others are
219     ignored.
220
221     This functionality is enabled by default but can be disabled via
222     the --no_logging_squelch_repeats commandline flag.
223
224     """
225
226     def __init__(self) -> None:
227         super().__init__()
228         self.counters: collections.Counter = collections.Counter()
229
230     @overrides
231     def filter(self, record: logging.LogRecord) -> bool:
232         id1 = f'{record.module}:{record.funcName}'
233         if id1 not in squelched_logging_counts:
234             return True
235         threshold = squelched_logging_counts[id1]
236         logsite = f'{record.pathname}+{record.lineno}+{record.levelno}+{record.msg}'
237         count = self.counters[logsite]
238         self.counters[logsite] += 1
239         return count < threshold
240
241
242 class DynamicPerScopeLoggingLevelFilter(logging.Filter):
243     """This filter only allows logging messages from an allow list of
244     module names or module:function names.  Blocks others.
245
246     """
247
248     @staticmethod
249     def level_name_to_level(name: str) -> int:
250         numeric_level = getattr(logging, name, None)
251         if not isinstance(numeric_level, int):
252             raise ValueError(f'Invalid level: {name}')
253         return numeric_level
254
255     def __init__(
256         self,
257         default_logging_level: int,
258         per_scope_logging_levels: str,
259     ) -> None:
260         super().__init__()
261         self.valid_levels = set(['NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'])
262         self.default_logging_level = default_logging_level
263         self.level_by_scope = {}
264         if per_scope_logging_levels is not None:
265             for chunk in per_scope_logging_levels.split(','):
266                 if '=' not in chunk:
267                     print(
268                         f'Malformed lmodule directive: "{chunk}", missing "=".  Ignored.',
269                         file=sys.stderr,
270                     )
271                     continue
272                 try:
273                     (scope, level) = chunk.split('=')
274                 except ValueError:
275                     print(
276                         f'Malformed lmodule directive: "{chunk}".  Ignored.',
277                         file=sys.stderr,
278                     )
279                     continue
280                 scope = scope.strip()
281                 level = level.strip().upper()
282                 if level not in self.valid_levels:
283                     print(
284                         f'Malformed lmodule directive: "{chunk}", bad level.  Ignored.',
285                         file=sys.stderr,
286                     )
287                     continue
288                 self.level_by_scope[scope] = DynamicPerScopeLoggingLevelFilter.level_name_to_level(
289                     level
290                 )
291
292     @overrides
293     def filter(self, record: logging.LogRecord) -> bool:
294         # First try to find a logging level by scope (--lmodule)
295         if len(self.level_by_scope) > 0:
296             min_level = None
297             for scope in (
298                 record.module,
299                 f'{record.module}:{record.funcName}',
300                 f':{record.funcName}',
301             ):
302                 level = self.level_by_scope.get(scope, None)
303                 if level is not None:
304                     if min_level is None or level < min_level:
305                         min_level = level
306
307             # If we found one, use it instead of the global default level.
308             if min_level is not None:
309                 return record.levelno >= min_level
310
311         # Otherwise, use the global logging level (--logging_level)
312         return record.levelno >= self.default_logging_level
313
314
315 # A map from function_identifier -> probability of logging (0.0%..100.0%)
316 probabilistic_logging_levels: Dict[str, float] = {}
317
318
319 def logging_is_probabilistic(probability_of_logging: float) -> Callable:
320     """
321     A decorator that indicates that all logging statements within the
322     scope of a particular (marked) function are not deterministic
323     (i.e. they do not always unconditionally log) but rather are
324     probabilistic (i.e. they log N% of the time randomly).
325
326     Note that this functionality can be disabled (forcing all logged
327     messages to produce output) via the --no_logging_probabilistically
328     cmdline argument.
329
330     This affects *ALL* logging statements within the marked function.
331
332     """
333
334     def probabilistic_logging_wrapper(f: Callable):
335         import function_utils
336
337         identifier = function_utils.function_identifier(f)
338         probabilistic_logging_levels[identifier] = probability_of_logging
339         return f
340
341     return probabilistic_logging_wrapper
342
343
344 class ProbabilisticFilter(logging.Filter):
345     """
346     A filter that logs messages probabilistically (i.e. randomly at some
347     percent chance).
348
349     This filter only affects logging messages from functions that have
350     been tagged with the @logging_utils.probabilistic_logging decorator.
351
352     """
353
354     @overrides
355     def filter(self, record: logging.LogRecord) -> bool:
356         id1 = f'{record.module}:{record.funcName}'
357         if id1 not in probabilistic_logging_levels:
358             return True
359         threshold = probabilistic_logging_levels[id1]
360         return (random.random() * 100.0) <= threshold
361
362
363 class OnlyInfoFilter(logging.Filter):
364     """
365     A filter that only logs messages produced at the INFO logging
366     level.  This is used by the logging_info_is_print commandline
367     option to select a subset of the logging stream to send to a
368     stdout handler.
369
370     """
371
372     @overrides
373     def filter(self, record: logging.LogRecord):
374         return record.levelno == logging.INFO
375
376
377 class MillisecondAwareFormatter(logging.Formatter):
378     """
379     A formatter for adding milliseconds to log messages which, for
380     whatever reason, the default python logger doesn't do.
381
382     """
383
384     converter = datetime.datetime.fromtimestamp  # type: ignore
385
386     @overrides
387     def formatTime(self, record, datefmt=None):
388         ct = MillisecondAwareFormatter.converter(record.created, pytz.timezone("US/Pacific"))
389         if datefmt:
390             s = ct.strftime(datefmt)
391         else:
392             t = ct.strftime("%Y-%m-%d %H:%M:%S")
393             s = f"{t},{record.msecs:%03d}"
394         return s
395
396
397 def log_about_logging(
398     logger,
399     default_logging_level,
400     preexisting_handlers_count,
401     fmt,
402     facility_name,
403 ):
404     level_name = logging._levelToName.get(default_logging_level, str(default_logging_level))
405     logger.debug(f'Initialized global logging; default logging level is {level_name}.')
406     if config.config['logging_clear_preexisting_handlers'] and preexisting_handlers_count > 0:
407         msg = f'Logging cleared {preexisting_handlers_count} global handlers (--logging_clear_preexisting_handlers)'
408         logger.warning(msg)
409     logger.debug(f'Logging format specification is "{fmt}"')
410     if config.config['logging_debug_threads']:
411         logger.debug('...Logging format spec captures tid/pid (--logging_debug_threads)')
412     if config.config['logging_debug_modules']:
413         logger.debug(
414             '...Logging format spec captures files/functions/lineno (--logging_debug_modules)'
415         )
416     if config.config['logging_syslog']:
417         logger.debug(f'Logging to syslog as {facility_name} with priority mapping based on level')
418     if config.config['logging_filename']:
419         logger.debug(f'Logging to filename {config.config["logging_filename"]}')
420         logger.debug(f'...with {config.config["logging_filename_maxsize"]} bytes max file size.')
421         logger.debug(
422             f'...and {config.config["logging_filename_count"]} rotating backup file count.'
423         )
424     if config.config['logging_console']:
425         logger.debug('Logging to the console (stderr).')
426     if config.config['logging_info_is_print']:
427         logger.debug(
428             'Logging logger.info messages will be repeated on stdout (--logging_info_is_print)'
429         )
430     if config.config['logging_squelch_repeats']:
431         logger.debug(
432             'Logging code allowed to request repeated messages be squelched (--logging_squelch_repeats)'
433         )
434     else:
435         logger.debug(
436             'Logging code forbidden to request messages be squelched; all messages logged (--no_logging_squelch_repeats)'
437         )
438     if config.config['logging_probabilistically']:
439         logger.debug(
440             'Logging code is allowed to request probabilistic logging (--logging_probabilistically)'
441         )
442     else:
443         logger.debug(
444             'Logging code is forbidden to request probabilistic logging; messages always logged (--no_logging_probabilistically)'
445         )
446     if config.config['lmodule']:
447         logger.debug(
448             f'Logging dynamic per-module logging enabled (--lmodule={config.config["lmodule"]})'
449         )
450     if config.config['logging_captures_prints']:
451         logger.debug(
452             'Logging will capture printed data as logger.info messages (--logging_captures_prints)'
453         )
454
455
456 def initialize_logging(logger=None) -> logging.Logger:
457     global LOGGING_INITIALIZED
458     if LOGGING_INITIALIZED:
459         return logging.getLogger()
460     LOGGING_INITIALIZED = True
461
462     if logger is None:
463         logger = logging.getLogger()
464
465     preexisting_handlers_count = 0
466     assert config.has_been_parsed()
467     if config.config['logging_clear_preexisting_handlers']:
468         while logger.hasHandlers():
469             logger.removeHandler(logger.handlers[0])
470             preexisting_handlers_count += 1
471
472     if config.config['logging_config_file'] is not None:
473         fileConfig(config.config['logging_config_file'])
474         return logger
475
476     handlers: List[logging.Handler] = []
477     handler: Optional[logging.Handler] = None
478
479     # Global default logging level (--logging_level)
480     default_logging_level = getattr(logging, config.config['logging_level'].upper(), None)
481     if not isinstance(default_logging_level, int):
482         raise ValueError(f'Invalid level: {config.config["logging_level"]}')
483
484     if config.config['logging_format']:
485         fmt = config.config['logging_format']
486     else:
487         if config.config['logging_syslog']:
488             fmt = '%(levelname).1s:%(filename)s[%(process)d]: %(message)s'
489         else:
490             fmt = '%(levelname).1s:%(asctime)s: %(message)s'
491     if config.config['logging_debug_threads']:
492         fmt = f'%(process)d.%(thread)d|{fmt}'
493     if config.config['logging_debug_modules']:
494         fmt = f'%(filename)s:%(funcName)s:%(lineno)s|{fmt}'
495
496     facility_name = None
497     if config.config['logging_syslog']:
498         if sys.platform not in ('win32', 'cygwin'):
499             if config.config['logging_syslog_facility']:
500                 facility_name = 'LOG_' + config.config['logging_syslog_facility']
501             facility = SysLogHandler.__dict__.get(facility_name, SysLogHandler.LOG_USER)  # type: ignore
502             assert facility is not None
503             handler = SysLogHandler(facility=facility, address='/dev/log')
504             handler.setFormatter(
505                 MillisecondAwareFormatter(
506                     fmt=fmt,
507                     datefmt=config.config['logging_date_format'],
508                 )
509             )
510             handlers.append(handler)
511
512     if config.config['logging_filename']:
513         handler = RotatingFileHandler(
514             config.config['logging_filename'],
515             maxBytes=config.config['logging_filename_maxsize'],
516             backupCount=config.config['logging_filename_count'],
517         )
518         handler.setFormatter(
519             MillisecondAwareFormatter(
520                 fmt=fmt,
521                 datefmt=config.config['logging_date_format'],
522             )
523         )
524         handlers.append(handler)
525
526     if config.config['logging_console']:
527         handler = logging.StreamHandler(sys.stderr)
528         handler.setFormatter(
529             MillisecondAwareFormatter(
530                 fmt=fmt,
531                 datefmt=config.config['logging_date_format'],
532             )
533         )
534         handlers.append(handler)
535
536     if len(handlers) == 0:
537         handlers.append(logging.NullHandler())
538
539     for handler in handlers:
540         logger.addHandler(handler)
541
542     if config.config['logging_info_is_print']:
543         handler = logging.StreamHandler(sys.stdout)
544         handler.addFilter(OnlyInfoFilter())
545         logger.addHandler(handler)
546
547     if config.config['logging_squelch_repeats']:
548         for handler in handlers:
549             handler.addFilter(SquelchRepeatedMessagesFilter())
550
551     if config.config['logging_probabilistically']:
552         for handler in handlers:
553             handler.addFilter(ProbabilisticFilter())
554
555     for handler in handlers:
556         handler.addFilter(
557             DynamicPerScopeLoggingLevelFilter(
558                 default_logging_level,
559                 config.config['lmodule'],
560             )
561         )
562     logger.setLevel(0)
563     logger.propagate = False
564
565     if config.config['logging_captures_prints']:
566         import builtins
567
568         def print_and_also_log(*arg, **kwarg):
569             f = kwarg.get('file', None)
570             if f == sys.stderr:
571                 logger.warning(*arg)
572             else:
573                 logger.info(*arg)
574             BUILT_IN_PRINT(*arg, **kwarg)
575
576         builtins.print = print_and_also_log
577
578     # At this point the logger is ready, handlers are set up,
579     # etc... so log about the logging configuration.
580     log_about_logging(
581         logger,
582         default_logging_level,
583         preexisting_handlers_count,
584         fmt,
585         facility_name,
586     )
587     return logger
588
589
590 def get_logger(name: str = ""):
591     logger = logging.getLogger(name)
592     return initialize_logging(logger)
593
594
595 def tprint(*args, **kwargs) -> None:
596     """Legacy function for printing a message augmented with thread id
597     still needed by some code.  Please use --logging_debug_threads in
598     new code.
599
600     """
601     if config.config['logging_debug_threads']:
602         from thread_utils import current_thread_id
603
604         print(f'{current_thread_id()}', end="")
605         print(*args, **kwargs)
606     else:
607         pass
608
609
610 def dprint(*args, **kwargs) -> None:
611     """Legacy function used to print to stderr still needed by some code.
612     Please just use normal logging with --logging_console which
613     accomplishes the same thing in new code.
614
615     """
616     print(*args, file=sys.stderr, **kwargs)
617
618
619 class OutputMultiplexer(object):
620     """
621     A class that broadcasts printed messages to several sinks (including
622     various logging levels, different files, different file handles,
623     the house log, etc...).  See also OutputMultiplexerContext for an
624     easy usage pattern.
625
626     """
627
628     class Destination(enum.IntEnum):
629         """Bits in the destination_bitv bitvector.  Used to indicate the
630         output destination."""
631
632         # fmt: off
633         LOG_DEBUG = 0x01     #  ⎫
634         LOG_INFO = 0x02      #  ⎪
635         LOG_WARNING = 0x04   #  ⎬ Must provide logger to the c'tor.
636         LOG_ERROR = 0x08     #  ⎪
637         LOG_CRITICAL = 0x10  #  ⎭
638         FILENAMES = 0x20     # Must provide a filename to the c'tor.
639         FILEHANDLES = 0x40   # Must provide a handle to the c'tor.
640         HLOG = 0x80
641         ALL_LOG_DESTINATIONS = (
642             LOG_DEBUG | LOG_INFO | LOG_WARNING | LOG_ERROR | LOG_CRITICAL
643         )
644         ALL_OUTPUT_DESTINATIONS = 0x8F
645         # fmt: on
646
647     def __init__(
648         self,
649         destination_bitv: int,
650         *,
651         logger=None,
652         filenames: Optional[Iterable[str]] = None,
653         handles: Optional[Iterable[io.TextIOWrapper]] = None,
654     ):
655         if logger is None:
656             logger = logging.getLogger(None)
657         self.logger = logger
658
659         self.f: Optional[List[Any]] = None
660         if filenames is not None:
661             self.f = [open(filename, 'wb', buffering=0) for filename in filenames]
662         else:
663             if destination_bitv & OutputMultiplexer.Destination.FILENAMES:
664                 raise ValueError("Filenames argument is required if bitv & FILENAMES")
665             self.f = None
666
667         self.h: Optional[List[Any]] = None
668         if handles is not None:
669             self.h = list(handles)
670         else:
671             if destination_bitv & OutputMultiplexer.Destination.FILEHANDLES:
672                 raise ValueError("Handle argument is required if bitv & FILEHANDLES")
673             self.h = None
674
675         self.set_destination_bitv(destination_bitv)
676
677     def get_destination_bitv(self):
678         return self.destination_bitv
679
680     def set_destination_bitv(self, destination_bitv: int):
681         if destination_bitv & self.Destination.FILENAMES and self.f is None:
682             raise ValueError("Filename argument is required if bitv & FILENAMES")
683         if destination_bitv & self.Destination.FILEHANDLES and self.h is None:
684             raise ValueError("Handle argument is required if bitv & FILEHANDLES")
685         self.destination_bitv = destination_bitv
686
687     def print(self, *args, **kwargs):
688         from string_utils import sprintf, strip_escape_sequences
689
690         end = kwargs.pop("end", None)
691         if end is not None:
692             if not isinstance(end, str):
693                 raise TypeError("end must be None or a string")
694         sep = kwargs.pop("sep", None)
695         if sep is not None:
696             if not isinstance(sep, str):
697                 raise TypeError("sep must be None or a string")
698         if kwargs:
699             raise TypeError("invalid keyword arguments to print()")
700         buf = sprintf(*args, end="", sep=sep)
701         if sep is None:
702             sep = " "
703         if end is None:
704             end = "\n"
705         if end == '\n':
706             buf += '\n'
707         if self.destination_bitv & self.Destination.FILENAMES and self.f is not None:
708             for _ in self.f:
709                 _.write(buf.encode('utf-8'))
710                 _.flush()
711
712         if self.destination_bitv & self.Destination.FILEHANDLES and self.h is not None:
713             for _ in self.h:
714                 _.write(buf)
715                 _.flush()
716
717         buf = strip_escape_sequences(buf)
718         if self.logger is not None:
719             if self.destination_bitv & self.Destination.LOG_DEBUG:
720                 self.logger.debug(buf)
721             if self.destination_bitv & self.Destination.LOG_INFO:
722                 self.logger.info(buf)
723             if self.destination_bitv & self.Destination.LOG_WARNING:
724                 self.logger.warning(buf)
725             if self.destination_bitv & self.Destination.LOG_ERROR:
726                 self.logger.error(buf)
727             if self.destination_bitv & self.Destination.LOG_CRITICAL:
728                 self.logger.critical(buf)
729         if self.destination_bitv & self.Destination.HLOG:
730             hlog(buf)
731
732     def close(self):
733         if self.f is not None:
734             for _ in self.f:
735                 _.close()
736
737
738 class OutputMultiplexerContext(OutputMultiplexer, contextlib.ContextDecorator):
739     """
740     A context that uses an OutputMultiplexer.  e.g.
741
742         with OutputMultiplexerContext(
743                 OutputMultiplexer.LOG_INFO |
744                 OutputMultiplexer.LOG_DEBUG |
745                 OutputMultiplexer.FILENAMES |
746                 OutputMultiplexer.FILEHANDLES,
747                 filenames = [ '/tmp/foo.log', '/var/log/bar.log' ],
748                 handles = [ f, g ]
749             ) as mplex:
750                 mplex.print("This is a log message!")
751
752     """
753
754     def __init__(
755         self,
756         destination_bitv: OutputMultiplexer.Destination,
757         *,
758         logger=None,
759         filenames=None,
760         handles=None,
761     ):
762         super().__init__(
763             destination_bitv,
764             logger=logger,
765             filenames=filenames,
766             handles=handles,
767         )
768
769     def __enter__(self):
770         return self
771
772     def __exit__(self, etype, value, traceback) -> bool:
773         super().close()
774         if etype is not None:
775             return False
776         return True
777
778
779 def hlog(message: str) -> None:
780     """Write a message to the house log (syslog facility local7 priority
781     info) by calling /usr/bin/logger.  This is pretty hacky but used
782     by a bunch of code.  Another way to do this would be to use
783     --logging_syslog and --logging_syslog_facility but I can't
784     actually say that's easier.
785
786     """
787     message = message.replace("'", "'\"'\"'")
788     os.system(f"/usr/bin/logger -p local7.info -- '{message}'")
789
790
791 if __name__ == '__main__':
792     import doctest
793
794     doctest.testmod()