From 44d18130b0e4a249124b9d59081aa7022aaed267 Mon Sep 17 00:00:00 2001 From: Tobias Klockau Date: Wed, 4 Oct 2023 16:18:52 +0200 Subject: [PATCH] fix: provide _warning code --- raillabel_providerkit/_util/__init__.py | 2 ++ raillabel_providerkit/_util/_warning.py | 37 +++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 raillabel_providerkit/_util/__init__.py create mode 100644 raillabel_providerkit/_util/_warning.py diff --git a/raillabel_providerkit/_util/__init__.py b/raillabel_providerkit/_util/__init__.py new file mode 100644 index 0000000..aabc64e --- /dev/null +++ b/raillabel_providerkit/_util/__init__.py @@ -0,0 +1,2 @@ +# Copyright DB Netz AG and contributors +# SPDX-License-Identifier: Apache-2.0 diff --git a/raillabel_providerkit/_util/_warning.py b/raillabel_providerkit/_util/_warning.py new file mode 100644 index 0000000..d501e0d --- /dev/null +++ b/raillabel_providerkit/_util/_warning.py @@ -0,0 +1,37 @@ +# Copyright DB Netz AG and contributors +# SPDX-License-Identifier: Apache-2.0 + +import logging +import typing as t +from io import StringIO + + +class _WarningsLogger: + + warnings: t.List[str] = [] + + def __enter__(self) -> "_WarningsLogger": + logger = logging.getLogger("loader_warnings") + warnings_stream = StringIO() + handler = logging.StreamHandler(warnings_stream) + handler.setLevel(logging.WARNING) + logger.addHandler(handler) + + return self + + def __exit__(self, exc_type, exc_value, traceback): + logger = logging.getLogger("loader_warnings") + stream = logger.handlers[-1].stream + stream.seek(0) + + warnings_list = stream.getvalue().split("\n") + + if len(warnings_list) > 0: + warnings_list = warnings_list[:-1] + + self.warnings = warnings_list + + +def _warning(message: str) -> logging.Logger: + """Create a loader warning.""" + logging.getLogger("loader_warnings").warning(message)