Coverage for abb_rws_client_python_rw6/core/logger.py: 100%
24 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-13 22:17 +0000
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-13 22:17 +0000
1# abb_rws_client/core/logger.py
2"""Centralised logging configuration for abb_rws_client_python_rw6.
4Author: Clement RACINET
6The entire library uses the standard :mod:`logging` module with loggers
7named after their module (``logging.getLogger(__name__)``). All of them
8are children of the root logger ``"abb_rws_client_python_rw6"``, so a single call to
9:func:`configure_logging` is enough to control verbosity for the whole
10library without touching the application's own loggers.
12Default behaviour (no call to :func:`configure_logging`):
13 The ``"abb_rws_client_python_rw6"`` logger has **no handler and no level set**,
14 which means it inherits from the root Python logger. In practice the
15 library is silent unless the caller configures logging themselves.
17Typical usage — application code::
19 from abb_rws_client_python_rw6import configure_logging
20 configure_logging(level="DEBUG")
22Typical usage — examples / scripts::
24 import os
25 from abb_rws_client_python_rw6import configure_logging
26 configure_logging(level=os.getenv("RWS_LOG_LEVEL", "INFO"))
28Typical usage — tests (silence the library)::
30 from abb_rws_client_python_rw6import configure_logging
31 configure_logging(level="WARNING")
32"""
34from __future__ import annotations
36import logging
37import sys
38from typing import TextIO
40#: Name of the library root logger. Every sub-logger (``core.client``,
41#: ``highlevel.rapid``, ``rws.rapid.execution``, …) is a child of this one.
42_ROOT_LOGGER_NAME: str = "abb_rws_client_python_rw6"
44#: Default format string used when no *fmt* argument is provided.
45_DEFAULT_FMT: str = "%(asctime)s [%(levelname)-8s] %(name)s — %(message)s"
46_DEFAULT_DATE_FMT: str = "%H:%M:%S"
49def configure_logging(
50 level: int | str = logging.WARNING,
51 fmt: str = _DEFAULT_FMT,
52 date_fmt: str = _DEFAULT_DATE_FMT,
53 handler: logging.Handler | None = None,
54 stream: TextIO = sys.stderr,
55) -> logging.Logger:
56 """Configure the ``abb_rws_client`` root logger.
58 Installs a :class:`logging.StreamHandler` (or a custom *handler*) on
59 the ``"abb_rws_client_python_rw6"`` logger and sets its level. Calling this
60 function more than once replaces the existing handlers.
62 All child loggers (``abb_rws_client_python_rw6.core.client``,
63 ``abb_rws_client_python_rw6.highlevel.*``, ``abb_rws_client_python_rw6.rws.*``, …)
64 inherit this configuration automatically — no per-module setup needed.
66 Args:
67 level: Logging level for the library. Accepts an integer
68 (e.g. ``logging.DEBUG``) or a string (e.g. ``"DEBUG"``,
69 ``"INFO"``, ``"WARNING"``). Defaults to ``logging.WARNING``
70 (silent in production).
71 fmt: Log record format string (``logging`` style).
72 Defaults to ``"%(asctime)s [%(levelname)-8s] %(name)s — %(message)s"``.
73 date_fmt: Date/time format string passed to the formatter.
74 Defaults to ``"%H:%M:%S"``.
75 handler: Custom :class:`logging.Handler` to attach. When
76 ``None`` a :class:`logging.StreamHandler` writing to *stream*
77 is created automatically.
78 stream: Output stream used when *handler* is ``None``.
79 Defaults to :data:`sys.stderr`.
81 Returns:
82 The configured ``"abb_rws_client_python_rw6"`` :class:`logging.Logger`
83 instance (useful for immediate use or further customisation).
85 Raises:
86 ValueError: If *level* is a string that is not a recognised
87 logging level name.
89 Example:
90 Basic setup for a script::
92 from abb_rws_client_python_rw6import configure_logging
93 configure_logging(level="DEBUG")
95 Custom handler (e.g. file)::
97 import logging
98 from abb_rws_client_python_rw6import configure_logging
100 fh = logging.FileHandler("rws.log")
101 configure_logging(level="INFO", handler=fh)
103 Read level from environment::
105 import os
106 from abb_rws_client_python_rw6import configure_logging
107 configure_logging(level=os.getenv("RWS_LOG_LEVEL", "WARNING"))
108 """
109 # Resolve string level → int (raises ValueError on unknown name)
110 if isinstance(level, str):
111 numeric = logging.getLevelName(level.upper())
112 if not isinstance(numeric, int):
113 raise ValueError(
114 f"Unknown logging level: {level!r}. "
115 f"Expected one of DEBUG, INFO, WARNING, ERROR, CRITICAL."
116 )
117 level = numeric
119 lib_logger = logging.getLogger(_ROOT_LOGGER_NAME)
121 # Replace existing handlers to avoid duplicate output on repeated calls.
122 lib_logger.handlers.clear()
124 if handler is None:
125 handler = logging.StreamHandler(stream)
127 handler.setFormatter(logging.Formatter(fmt=fmt, datefmt=date_fmt))
128 lib_logger.addHandler(handler)
129 lib_logger.setLevel(level)
131 # Do not propagate to the root Python logger — the library manages its
132 # own output and should not interfere with the application's log config.
133 lib_logger.propagate = False
135 return lib_logger
138def get_logger(name: str) -> logging.Logger:
139 """Return a child logger of ``"abb_rws_client_python_rw6"``.
141 Convenience wrapper so that any module — including user code and
142 example scripts — can obtain a properly namespaced logger without
143 hard-coding the root name.
145 Args:
146 name: Sub-name appended to ``"abb_rws_client_python_rw6."``.
147 Typically ``__name__`` of the calling module, or a short
148 descriptive label (e.g. ``"examples.ping"``).
150 Returns:
151 A :class:`logging.Logger` named
152 ``"abb_rws_client_python_rw6.<name>"``.
154 Example:
155 Inside a library module::
157 from abb_rws_client_python_rw6.core.logger import get_logger
158 logger = get_logger(__name__)
160 Inside an example script::
162 from abb_rws_client_python_rw6import get_logger
163 logger = get_logger("examples.ping")
164 """
165 return logging.getLogger(f"{_ROOT_LOGGER_NAME}.{name}")