Coverage for trlcdoc/log.py: 94%
51 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-28 14:00 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-28 14:00 +0000
1"""Console output of trlcdoc: logging setup, verbosity levels and redaction of secrets.
3All trlcdoc modules log with logging.getLogger(__name__), below the 'trlcdoc' logger configured here.
4INFO is the default output, DEBUG (-v) adds decisions and tool details, TRACE (-vv) adds per-item details.
5"""
7# trlcdoc - A utility for producing project documentation from TRLC and LOBSTER contents.
8# Copyright (c) 2026 - 2026 Norbert Schulz github@schulznorbert.de
9#
10# This file is part of trlcdoc program.
11#
12# The trlcdoc program is free software: you can redistribute it and/or modify it under
13# the terms of the GNU General Public License as published by the Free Software Foundation,
14# either version 3 of the License, or (at your option) any later version.
15#
16# The trlcdoc program is distributed in the hope that it will be useful, but
17# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License along with pyTRLCConverter.
21# If not, see <https://www.gnu.org/licenses/>.
23# Imports **********************************************************************
25import logging
26import re
27import shlex
28import subprocess
29import sys
30from urllib.parse import urlsplit, urlunsplit
32# Variables ********************************************************************
34# Level below DEBUG for per-item details, e.g. every rewritten link.
35TRACE = 5
36logging.addLevelName(TRACE, "TRACE")
38# Logger of the trlcdoc package, parent of the module loggers.
39LOGGER_NAME = "trlcdoc"
41# Log level per number of -v options.
42VERBOSITY_LEVELS = [logging.INFO, logging.DEBUG, TRACE]
44# Environment variables whose values are never logged.
45SECRET_NAME = re.compile(r"TOKEN|SECRET|PASSWORD|KEY|CREDENTIAL", re.IGNORECASE)
46REDACTED = "***"
48# Classes **********************************************************************
51class ConsoleHandler(logging.Handler):
52 # lobster-trace: SwRequirements.sw_req_verbose_output
53 """Write INFO and below to stdout, WARNING and above to stderr.
55 The stream is looked up for every message instead of once, so output redirected later,
56 e.g. by pytest, receives the messages. Every message is flushed, so it appears before
57 the output of a tool started next.
58 """
60 def emit(self, record: logging.LogRecord) -> None:
61 """Write a message to its stream.
63 Args:
64 record (logging.LogRecord): The message.
65 """
66 try:
67 stream = sys.stderr if record.levelno >= logging.WARNING else sys.stdout
68 stream.write(self.format(record) + "\n")
69 stream.flush()
70 except Exception:
71 # The logging module's way to report a failing handler, as logging.StreamHandler does.
72 self.handleError(record)
75class LevelFormatter(logging.Formatter):
76 # lobster-trace: SwRequirements.sw_req_verbose_output
77 """Format a message unchanged, and prefix debug and trace messages with their level name.
79 The default output keeps its plain text, the verbose lines are recognizable.
80 """
82 def format(self, record: logging.LogRecord) -> str:
83 """Format a message.
85 Args:
86 record (logging.LogRecord): The message.
88 Returns:
89 str: The message, with 'DEBUG: ' or 'TRACE: ' in front for verbose messages.
90 """
91 message = record.getMessage()
92 if record.levelno < logging.INFO:
93 message = f"{record.levelname}: {message}"
94 return message
97# Functions ********************************************************************
100def setup_logging(verbosity: int = 0) -> None:
101 # lobster-trace: SwRequirements.sw_req_verbose_output
102 """Configure the trlcdoc logger for the console.
104 It can be called again, e.g. for each run in the tests: the handler is replaced, not added.
106 Args:
107 verbosity (int): Number of -v options: 0 for the default output, 1 for DEBUG, 2 or more for TRACE.
108 """
109 logger = logging.getLogger(LOGGER_NAME)
110 for handler in list(logger.handlers):
111 logger.removeHandler(handler)
112 handler = ConsoleHandler()
113 handler.setFormatter(LevelFormatter())
114 logger.addHandler(handler)
115 logger.setLevel(VERBOSITY_LEVELS[min(verbosity, len(VERBOSITY_LEVELS) - 1)])
116 # Applications using the root logger, e.g. Sphinx, would print the messages a second time.
117 logger.propagate = False
120def redact_url(text: str) -> str:
121 # lobster-trace: SwRequirements.sw_req_verbose_output
122 """Replace the user and password of a URL, e.g. of a PlantUML server.
124 Args:
125 text (str): A URL or any other text.
127 Returns:
128 str: The text, with ``***`` instead of the user info if it is a URL with one.
129 """
130 parts = urlsplit(text)
131 if "@" not in parts.netloc:
132 return text
133 host = parts.netloc.rsplit("@", 1)[1]
134 return urlunsplit(parts._replace(netloc=f"{REDACTED}@{host}"))
137def redact_env(env: dict[str, str]) -> dict[str, str]:
138 # lobster-trace: SwRequirements.sw_req_verbose_output
139 """Replace the secrets of environment variables.
141 Args:
142 env (dict[str, str]): Environment variables.
144 Returns:
145 dict[str, str]: A copy with ``***`` as value of variables named like a secret, and URLs without user info.
146 """
147 redacted = {}
148 for name, value in env.items():
149 redacted[name] = REDACTED if SECRET_NAME.search(name) else redact_url(value)
150 return redacted
153def command_line(cmd: list[str]) -> str:
154 # lobster-trace: SwRequirements.sw_req_verbose_output
155 """Format a command so it can be pasted into a shell of the system.
157 Args:
158 cmd (list[str]): Command and its arguments.
160 Returns:
161 str: The command line, quoted for cmd.exe on Windows and for a POSIX shell elsewhere.
162 """
163 if sys.platform == "win32":
164 return subprocess.list2cmdline(cmd)
165 return shlex.join(cmd)
168# Main *************************************************************************
170# Functions called without the command line interface, e.g. by the tests, log with the default output.
171setup_logging()