pmt4api 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pmt4api/diagnostics.py ADDED
@@ -0,0 +1,38 @@
1
+ """Route the core's own diagnostics into Python's ``logging``."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ from typing import Any, Callable
6
+
7
+ from . import _runtime
8
+
9
+ _LEVELS = {"Trace": logging.DEBUG, "Debug": logging.DEBUG, "Info": logging.INFO, "Warn": logging.WARNING,
10
+ "Error": logging.ERROR, "Exception": logging.ERROR}
11
+
12
+
13
+ def enable_core_logging(logger_name: str = "pmt4api.core") -> Callable[[], None]:
14
+ """Forward the core's log messages (``Logger.OnMsgEx``) and internal diagnostics (``Diag.Sink``) to the Python
15
+ logger ``logger_name``. Returns a function that switches it off again. Nothing is forwarded unless this is called,
16
+ and the core is silent by default."""
17
+ core = _runtime.load()
18
+ import System # noqa: PLC0415
19
+ logger = logging.getLogger(logger_name)
20
+
21
+ def on_msg(sender: Any, msg: Any, kind: Any, ex: Any = None) -> None:
22
+ level = _LEVELS.get(str(kind), logging.INFO)
23
+ if logger.isEnabledFor(level):
24
+ logger.log(level, "%s%s", msg, (" | %s" % ex.Message) if ex is not None else "")
25
+
26
+ def on_diag(message: Any) -> None:
27
+ if logger.isEnabledFor(logging.DEBUG):
28
+ logger.debug("%s", message)
29
+
30
+ core.Logger.OnMsgEx += on_msg
31
+ sink = System.Action[System.String](on_diag)
32
+ previous = core.Diag.Sink
33
+ core.Diag.Sink = sink
34
+
35
+ def disable() -> None:
36
+ core.Logger.OnMsgEx -= on_msg
37
+ core.Diag.Sink = previous
38
+ return disable