diff --git a/slic/utils/__init__.py b/slic/utils/__init__.py index 0f990bbc8..f510d3d8c 100644 --- a/slic/utils/__init__.py +++ b/slic/utils/__init__.py @@ -11,6 +11,7 @@ from .eval import arithmetic_eval, defaulting_eval, forgiving_eval from .exceptions import ChainedException, printable_exception, printed_exception from .ipy import devices from .jsonext import json_save, json_load, json_validate +from .logign import ignore_log_msg from .marker import Marker, markers from .namespace import Namespace from .npy import nice_linspace, nice_arange, fraction_to_percentage, within, within_fraction, get_dtype, get_shape, is_array diff --git a/slic/utils/logign.py b/slic/utils/logign.py new file mode 100644 index 000000000..3041fdc29 --- /dev/null +++ b/slic/utils/logign.py @@ -0,0 +1,49 @@ +import logging +from contextlib import contextmanager + + +#MISSING_TYPE = "'type' channel field not found. Parse as 64-bit floating-point number float64 (default)." +#with source(channels=channels, receive_timeout=-1) as src: +# with ignore_log_msg("bsread.data.helpers", lvl=logging.WARNING, msg=MISSING_TYPE): +# src.receive() + + +def ignore_log_msg(log, lvl=None, msg=None): + """ + ignore log messages with matching lvl and msg + log must be a logger or a logger name + None for lvl or msg are interpreted as any level or any message + """ + logger = logging.getLogger(log) if isinstance(log, str) else log + filt = IgnoreMessagesFilter(lvl=lvl, msg=msg) + return log_filter(logger, filt) + + +@contextmanager +def log_filter(logger, filt): + logger.addFilter(filt) + try: + yield + finally: + logger.removeFilter(filt) + + + +class IgnoreMessagesFilter(logging.Filter): + + def __init__(self, lvl=None, msg=None): + self.lvl = lvl + self.msg = msg + + + def filter(self, record): + lvl = self.lvl + msg = self.msg + + is_lvl = (lvl is None or lvl == record.levelno) + is_msg = (msg is None or msg == record.msg) + + return not (is_lvl and is_msg) + + +