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 <jan@janware.com>
This commit is contained in:
Jan Lindemann 2020-05-16 15:33:13 +00:00
commit 8029b672bf

View file

@ -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):