|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import sys |
1 | 4 | from importlib.metadata import PackageNotFoundError, version # pragma: no cover |
2 | 5 |
|
3 | 6 | try: |
|
8 | 11 | __version__ = "unknown" |
9 | 12 | finally: |
10 | 13 | del version, PackageNotFoundError |
| 14 | + |
| 15 | +LOG_LEVEL_ENV_VAR = "OSW_LOG_LEVEL" |
| 16 | +"""Name of the environment variable read for the initial log level. Accepts a |
| 17 | +level name, a level number, or 'OFF' to start silent.""" |
| 18 | +DEFAULT_LOG_LEVEL = logging.INFO |
| 19 | +"""Level the osw logger starts at when the environment variable is unset""" |
| 20 | +LOG_FORMAT = "[%(levelname)s] %(name)s: %(message)s" |
| 21 | +OFF = logging.CRITICAL + 1 |
| 22 | +"""Level above every real record, so setting it silences the logger""" |
| 23 | + |
| 24 | +_DEFAULT_HANDLER_NAME = "osw-default" |
| 25 | +_logger = logging.getLogger(__name__) |
| 26 | +_level_is_ours = False |
| 27 | +"""Whether the level on the osw logger is the one osw picked for itself. A |
| 28 | +level the calling code asked for is left alone when osw hands over.""" |
| 29 | + |
| 30 | + |
| 31 | +def _parse_level(value: str) -> int: |
| 32 | + """Turns the environment variable into a level, tolerating junk |
| 33 | +
|
| 34 | + Parameters |
| 35 | + ---------- |
| 36 | + value |
| 37 | + a level name such as 'DEBUG', a level number such as '10', or 'OFF' |
| 38 | +
|
| 39 | + Returns |
| 40 | + ------- |
| 41 | + the level, or DEFAULT_LOG_LEVEL if the value names none |
| 42 | + """ |
| 43 | + cleaned = value.strip().upper() |
| 44 | + if cleaned in ("OFF", "NONE", "SILENT"): |
| 45 | + return OFF |
| 46 | + if cleaned.isdigit(): |
| 47 | + return int(cleaned) |
| 48 | + # getLevelName maps an unknown name to the string 'Level %s', not to a number |
| 49 | + level = logging.getLevelName(cleaned) |
| 50 | + if isinstance(level, int): |
| 51 | + return level |
| 52 | + return DEFAULT_LOG_LEVEL |
| 53 | + |
| 54 | + |
| 55 | +def _application_handles_records() -> bool: |
| 56 | + """Whether the calling code already has somewhere for osw's records to go |
| 57 | +
|
| 58 | + Walks what logging.Logger.callHandlers walks above the osw logger. Any |
| 59 | + handler found up there belongs to the calling application, so osw writing |
| 60 | + its own copy would only duplicate what that handler already reports. |
| 61 | + """ |
| 62 | + if not _logger.propagate: |
| 63 | + # something is deliberately holding the records at the osw logger, |
| 64 | + # parallelize while it captures a batch among them |
| 65 | + return False |
| 66 | + current = _logger.parent |
| 67 | + while current: |
| 68 | + if current.handlers: |
| 69 | + return True |
| 70 | + if not current.propagate: |
| 71 | + return False |
| 72 | + current = current.parent |
| 73 | + return False |
| 74 | + |
| 75 | + |
| 76 | +class _DefaultHandler(logging.StreamHandler): |
| 77 | + """The handler osw attaches while nothing else is listening |
| 78 | +
|
| 79 | + Steps aside the first time it finds that the calling application has |
| 80 | + configured logging of its own. The check belongs here rather than at import |
| 81 | + time because a script normally imports osw before it calls basicConfig(). |
| 82 | + """ |
| 83 | + |
| 84 | + def emit(self, record: logging.LogRecord): |
| 85 | + if _application_handles_records(): |
| 86 | + _hand_over() |
| 87 | + return |
| 88 | + super().emit(record) |
| 89 | + |
| 90 | + |
| 91 | +def _detach(): |
| 92 | + """Removes the handler osw attached, leaving any other one in place |
| 93 | +
|
| 94 | + Rebinds the list instead of calling removeHandler, because this also runs |
| 95 | + from inside the handler's own emit, where callHandlers is iterating that |
| 96 | + very list. |
| 97 | + """ |
| 98 | + detached = [h for h in _logger.handlers if h.get_name() == _DEFAULT_HANDLER_NAME] |
| 99 | + _logger.handlers = [h for h in _logger.handlers if h not in detached] |
| 100 | + for handler in detached: |
| 101 | + handler.close() |
| 102 | + |
| 103 | + |
| 104 | +def _hand_over(): |
| 105 | + """Gives the application's own logging setup sole charge of osw's records |
| 106 | +
|
| 107 | + Drops osw's handler so nothing is written twice, and drops the level osw |
| 108 | + picked so the application's level applies. A level the calling code asked |
| 109 | + for, through set_log_level, enable_logging or the environment variable, is |
| 110 | + kept, since that is how one asks for osw's DEBUG records in an aggregated |
| 111 | + setup. |
| 112 | + """ |
| 113 | + global _level_is_ours |
| 114 | + _detach() |
| 115 | + if _level_is_ours: |
| 116 | + _logger.setLevel(logging.NOTSET) |
| 117 | + _level_is_ours = False |
| 118 | + |
| 119 | + |
| 120 | +def enable_logging(level=None, stream=None) -> logging.Handler: |
| 121 | + """Attaches osw's own handler to the osw logger |
| 122 | +
|
| 123 | + Called on import when nothing else handles the records, so osw reports what |
| 124 | + it is doing without the calling code configuring anything. Call it again to |
| 125 | + take the output back after disable_logging(), or to send it elsewhere. |
| 126 | +
|
| 127 | + The handler detaches itself as soon as the calling application configures |
| 128 | + logging, so records are never written twice. |
| 129 | +
|
| 130 | + Parameters |
| 131 | + ---------- |
| 132 | + level |
| 133 | + a level name or number. Defaults to the environment variable, then to |
| 134 | + DEFAULT_LOG_LEVEL. |
| 135 | + stream |
| 136 | + where to write. Defaults to sys.stderr, so stdout stays free for a |
| 137 | + program's own output. Anything speaking a protocol over stdout, such as |
| 138 | + an MCP stdio server, depends on that. |
| 139 | +
|
| 140 | + Returns |
| 141 | + ------- |
| 142 | + the attached handler |
| 143 | + """ |
| 144 | + global _level_is_ours |
| 145 | + asked_for = level is not None or LOG_LEVEL_ENV_VAR in os.environ |
| 146 | + if level is None: |
| 147 | + level = _parse_level(os.environ.get(LOG_LEVEL_ENV_VAR, "")) |
| 148 | + _detach() |
| 149 | + handler = _DefaultHandler(sys.stderr if stream is None else stream) |
| 150 | + handler.setFormatter(logging.Formatter(LOG_FORMAT)) |
| 151 | + handler.set_name(_DEFAULT_HANDLER_NAME) |
| 152 | + _logger.addHandler(handler) |
| 153 | + _logger.setLevel(level) |
| 154 | + _level_is_ours = not asked_for |
| 155 | + return handler |
| 156 | + |
| 157 | + |
| 158 | +def disable_logging(): |
| 159 | + """Hands the osw logger over to the calling application |
| 160 | +
|
| 161 | + Removes the handler osw attached and the level it picked, so the records |
| 162 | + follow whatever the application configured, on the 'osw' logger or on the |
| 163 | + root logger above it. A handler the calling code added to the 'osw' logger |
| 164 | + is left in place. |
| 165 | +
|
| 166 | + Not needed in order to aggregate osw's records. They propagate to the root |
| 167 | + logger at all times, and osw's own handler steps aside by itself once |
| 168 | + anything else is listening. Call this to be explicit about it, or when a |
| 169 | + handler was added to the 'osw' logger directly, which osw cannot tell apart |
| 170 | + from one of its own callers. |
| 171 | + """ |
| 172 | + global _level_is_ours |
| 173 | + _detach() |
| 174 | + _logger.setLevel(logging.NOTSET) |
| 175 | + _level_is_ours = False |
| 176 | + |
| 177 | + |
| 178 | +def set_log_level(level): |
| 179 | + """Sets how much osw reports |
| 180 | +
|
| 181 | + The level survives a hand-over to the application's own logging setup, so |
| 182 | + this is also how to ask for osw's DEBUG records in an aggregated setup. |
| 183 | +
|
| 184 | + Parameters |
| 185 | + ---------- |
| 186 | + level |
| 187 | + a level name or number, e.g. 'DEBUG', 'WARNING', or logging.WARNING. |
| 188 | + Pass osw.OFF to silence osw everywhere, its own handler and the |
| 189 | + application's alike. |
| 190 | + """ |
| 191 | + global _level_is_ours |
| 192 | + _logger.setLevel(level) |
| 193 | + _level_is_ours = False |
| 194 | + |
| 195 | + |
| 196 | +def _configure_on_import(): |
| 197 | + """Sets logging up the way an interpreter that configured none needs it""" |
| 198 | + if _application_handles_records(): |
| 199 | + # logging was configured before osw was imported, so the records |
| 200 | + # already have somewhere to go and only the level is osw's to set |
| 201 | + if LOG_LEVEL_ENV_VAR in os.environ: |
| 202 | + set_log_level(_parse_level(os.environ[LOG_LEVEL_ENV_VAR])) |
| 203 | + return |
| 204 | + enable_logging() |
| 205 | + if LOG_LEVEL_ENV_VAR not in os.environ: |
| 206 | + # once per interpreter, since this module is imported once. Sent |
| 207 | + # through the logger itself, so it disappears with everything else as |
| 208 | + # soon as the level is raised or the environment variable is set. |
| 209 | + _logger.info( |
| 210 | + "osw logs at %s on the 'osw' logger. Use osw.set_log_level" |
| 211 | + "('WARNING') to see less, osw.disable_logging() to switch it off, " |
| 212 | + "or set %s=OFF before import. Configuring logging yourself, e.g. " |
| 213 | + "with logging.basicConfig(), takes the output over automatically.", |
| 214 | + logging.getLevelName(_logger.level), |
| 215 | + LOG_LEVEL_ENV_VAR, |
| 216 | + ) |
| 217 | + |
| 218 | + |
| 219 | +_configure_on_import() |
0 commit comments