From 8029b672bff9c61f84a9f71cfffaf7fe03094708 Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Sat, 16 May 2020 15:33:13 +0000 Subject: [PATCH] slog(): Add only_printable keyword argument Add only_printable keyword argument to slog(). It defaults to False. If it's true, non-printable characters are not logged but replaced with a printable character. Signed-off-by: Jan Lindemann --- tools/python/jwutils/log.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/tools/python/jwutils/log.py b/tools/python/jwutils/log.py index 2d3b7f7..b3219bc 100644 --- a/tools/python/jwutils/log.py +++ b/tools/python/jwutils/log.py @@ -2,6 +2,7 @@ from __future__ import print_function import syslog import sys import inspect +import re from os.path import basename from datetime import datetime from typing import List, Tuple @@ -13,6 +14,18 @@ try: except NameError: basestring = str +_special_chars = { + '\a' : '\\a', + '\b' : '\\b', + '\t' : '\\t', + '\n' : '\\n', + '\v' : '\\v', + '\f' : '\\f', + '\r' : '\\r', +} + +_special_char_regex = re.compile("(%s)" % "|".join(map(re.escape, _special_chars.keys()))) + EMERG = syslog.LOG_EMERG ALERT = syslog.LOG_ALERT CRIT = syslog.LOG_CRIT @@ -101,7 +114,7 @@ def slog_m(prio: int, *args, **kwargs) -> None: # export for line in margs[1:].split('\n'): slog(prio, line, **kwargs, caller=caller) -def slog(prio: int, *args, **kwargs) -> None: # export +def slog(prio: int, *args, only_printable=False, **kwargs) -> None: # export if prio > _level: return @@ -132,6 +145,9 @@ def slog(prio: int, *args, **kwargs) -> None: # export margs = '' for a in args: margs += ' ' + str(a) + if only_printable: + margs = _special_char_regex.sub(lambda mo: _special_chars[mo.string[mo.start():mo.end()]], margs) + margs = re.sub('[\x01-\x1f]', '.', margs) msg += color_on + margs + color_off if not len(msg):