Coverage for python/lsst/daf/butler/cli/cliLog.py: 24%
156 statements
« prev ^ index » next coverage.py v7.5.0, created at 2024-04-24 23:50 -0700
« prev ^ index » next coverage.py v7.5.0, created at 2024-04-24 23:50 -0700
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
23__all__ = (
24 "PrecisionLogFormatter",
25 "CliLog",
26)
29import datetime
30import logging
31import os
32from typing import Dict, Optional, Set, Tuple
34try:
35 import lsst.log as lsstLog
36except ModuleNotFoundError:
37 lsstLog = None
39from lsst.utils.logging import TRACE, VERBOSE
41from ..core.logging import ButlerMDC, JsonLogFormatter
44class PrecisionLogFormatter(logging.Formatter):
45 """A log formatter that issues accurate timezone-aware timestamps."""
47 converter = datetime.datetime.fromtimestamp
49 use_local = True
50 """Control whether local time is displayed instead of UTC."""
52 def formatTime(self, record, datefmt=None):
53 """Format the time as an aware datetime."""
54 ct = self.converter(record.created, tz=datetime.timezone.utc)
55 if self.use_local:
56 ct = ct.astimezone()
57 if datefmt:
58 s = ct.strftime(datefmt)
59 else:
60 s = ct.isoformat(sep="T", timespec="milliseconds")
61 return s
64class CliLog:
65 """Interface for managing python logging and ``lsst.log``.
67 This class defines log format strings for the log output and timestamp
68 formats. It also configures ``lsst.log`` to forward all messages to
69 Python `logging`.
71 This class can perform log uninitialization, which allows command line
72 interface code that initializes logging to run unit tests that execute in
73 batches, without affecting other unit tests. See ``resetLog``."""
75 defaultLsstLogLevel = lsstLog.FATAL if lsstLog is not None else None
77 pylog_longLogFmt = "{levelname} {asctime} {name} ({MDC[LABEL]})({filename}:{lineno}) - {message}"
78 """The log format used when the lsst.log package is not importable and the
79 log is initialized with longlog=True."""
81 pylog_normalFmt = "{name} {levelname}: {message}"
82 """The log format used when the lsst.log package is not importable and the
83 log is initialized with longlog=False."""
85 configState = []
86 """Configuration state. Contains tuples where first item in a tuple is
87 a method and remaining items are arguments for the method.
88 """
90 _initialized = False
91 _componentSettings = []
93 _fileHandlers = []
94 """Any FileHandler classes attached to the root logger by this class
95 that need to be closed on reset."""
97 @staticmethod
98 def root_loggers() -> Set[str]:
99 """Return the default root logger.
101 Returns
102 -------
103 log_name : `set` of `str`
104 The name(s) of the root logger(s) to use when the log level is
105 being set without a log name being specified.
107 Notes
108 -----
109 The default is ``lsst`` (which controls the butler infrastructure)
110 but additional loggers can be specified by setting the environment
111 variable ``DAF_BUTLER_ROOT_LOGGER``. This variable can contain
112 multiple default loggers separated by a ``:``.
113 """
114 log_names = set(["lsst"])
115 envvar = "DAF_BUTLER_ROOT_LOGGER"
116 if envvar in os.environ: 116 ↛ 117line 116 didn't jump to line 117, because the condition on line 116 was never true
117 log_names |= set(os.environ[envvar].split(":"))
118 return log_names
120 @classmethod
121 def initLog(
122 cls,
123 longlog: bool,
124 log_tty: bool = True,
125 log_file: Tuple[str, ...] = (),
126 log_label: Optional[Dict[str, str]] = None,
127 ):
128 """Initialize logging. This should only be called once per program
129 execution. After the first call this will log a warning and return.
131 If lsst.log is importable, will add its log handler to the python
132 root logger's handlers.
134 Parameters
135 ----------
136 longlog : `bool`
137 If True, make log messages appear in long format, by default False.
138 log_tty : `bool`
139 Control whether a default stream handler is enabled that logs
140 to the terminal.
141 log_file : `tuple` of `str`
142 Path to files to write log records. If path ends in ``.json`` the
143 records will be written in JSON format. Else they will be written
144 in text format. If empty no log file will be created. Records
145 will be appended to this file if it exists.
146 log_label : `dict` of `str`
147 Keys and values to be stored in logging MDC for all JSON log
148 records. Keys will be upper-cased.
149 """
150 if cls._initialized:
151 # Unit tests that execute more than one command do end up
152 # calling this function multiple times in one program execution,
153 # so do log a debug but don't log an error or fail, just make the
154 # re-initialization a no-op.
155 log = logging.getLogger(__name__)
156 log.debug("Log is already initialized, returning without re-initializing.")
157 return
158 cls._initialized = True
159 cls._recordComponentSetting(None)
161 if lsstLog is not None:
162 # Ensure that log messages are forwarded back to python.
163 # Disable use of lsst.log MDC -- we expect butler uses to
164 # use ButlerMDC.
165 lsstLog.configure_pylog_MDC("DEBUG", MDC_class=None)
167 # Forward python lsst.log messages directly to python logging.
168 # This can bypass the C++ layer entirely but requires that
169 # MDC is set via ButlerMDC, rather than in lsst.log.
170 lsstLog.usePythonLogging()
172 if not log_tty:
173 logging.basicConfig(force=True, handlers=[logging.NullHandler()])
174 elif longlog:
175 # Want to create our own Formatter so that we can get high
176 # precision timestamps. This requires we attach our own
177 # default stream handler.
178 defaultHandler = logging.StreamHandler()
179 formatter = PrecisionLogFormatter(fmt=cls.pylog_longLogFmt, style="{")
180 defaultHandler.setFormatter(formatter)
182 logging.basicConfig(
183 level=logging.WARNING,
184 force=True,
185 handlers=[defaultHandler],
186 )
188 else:
189 logging.basicConfig(level=logging.WARNING, format=cls.pylog_normalFmt, style="{")
191 # Initialize the root logger. Calling this ensures that both
192 # python loggers and lsst loggers are consistent in their default
193 # logging level.
194 cls._setLogLevel(".", "WARNING")
196 # Initialize default root logger level.
197 cls._setLogLevel(None, "INFO")
199 # also capture warnings and send them to logging
200 logging.captureWarnings(True)
202 # Create a record factory that ensures that an MDC is attached
203 # to the records. By default this is only used for long-log
204 # but always enable it for when someone adds a new handler
205 # that needs it.
206 ButlerMDC.add_mdc_log_record_factory()
208 # Set up the file logger
209 for file in log_file:
210 handler = logging.FileHandler(file)
211 if file.endswith(".json"):
212 formatter = JsonLogFormatter()
213 else:
214 if longlog:
215 formatter = PrecisionLogFormatter(fmt=cls.pylog_longLogFmt, style="{")
216 else:
217 formatter = logging.Formatter(fmt=cls.pylog_normalFmt, style="{")
218 handler.setFormatter(formatter)
219 logging.getLogger().addHandler(handler)
220 cls._fileHandlers.append(handler)
222 # Add any requested MDC records.
223 if log_label:
224 for key, value in log_label.items():
225 ButlerMDC.MDC(key.upper(), value)
227 # remember this call
228 cls.configState.append((cls.initLog, longlog, log_tty, log_file, log_label))
230 @classmethod
231 def resetLog(cls):
232 """Uninitialize the butler CLI Log handler and reset component log
233 levels.
235 If the lsst.log handler was added to the python root logger's handlers
236 in `initLog`, it will be removed here.
238 For each logger level that was set by this class, sets that logger's
239 level to the value it was before this class set it. For lsst.log, if a
240 component level was uninitialized, it will be set to
241 `Log.defaultLsstLogLevel` because there is no log4cxx api to set a
242 component back to an uninitialized state.
243 """
244 if lsstLog:
245 lsstLog.doNotUsePythonLogging()
246 for componentSetting in reversed(cls._componentSettings):
247 if lsstLog is not None and componentSetting.lsstLogLevel is not None:
248 lsstLog.setLevel(componentSetting.component or "", componentSetting.lsstLogLevel)
249 logger = logging.getLogger(componentSetting.component)
250 logger.setLevel(componentSetting.pythonLogLevel)
251 cls._setLogLevel(None, "INFO")
253 ButlerMDC.restore_log_record_factory()
255 # Remove the FileHandler we may have attached.
256 root = logging.getLogger()
257 for handler in cls._fileHandlers:
258 handler.close()
259 root.removeHandler(handler)
261 cls._fileHandlers.clear()
262 cls._initialized = False
263 cls.configState = []
265 @classmethod
266 def setLogLevels(cls, logLevels):
267 """Set log level for one or more components or the root logger.
269 Parameters
270 ----------
271 logLevels : `list` of `tuple`
272 per-component logging levels, each item in the list is a tuple
273 (component, level), `component` is a logger name or an empty string
274 or `None` for default root logger, `level` is a logging level name,
275 one of CRITICAL, ERROR, WARNING, INFO, DEBUG (case insensitive).
277 Notes
278 -----
279 The special name ``.`` can be used to set the Python root
280 logger.
281 """
282 if isinstance(logLevels, dict):
283 logLevels = logLevels.items()
285 # configure individual loggers
286 for component, level in logLevels:
287 cls._setLogLevel(component, level)
288 # remember this call
289 cls.configState.append((cls._setLogLevel, component, level))
291 @classmethod
292 def _setLogLevel(cls, component, level):
293 """Set the log level for the given component. Record the current log
294 level of the component so that it can be restored when resetting this
295 log.
297 Parameters
298 ----------
299 component : `str` or None
300 The name of the log component or None for the default logger.
301 The root logger can be specified either by an empty string or
302 with the special name ``.``.
303 level : `str`
304 A valid python logging level.
305 """
306 components: Set[Optional[str]]
307 if component is None:
308 components = cls.root_loggers()
309 elif not component or component == ".":
310 components = {None}
311 else:
312 components = {component}
313 for component in components:
314 cls._recordComponentSetting(component)
315 if lsstLog is not None:
316 lsstLogger = lsstLog.Log.getLogger(component or "")
317 lsstLogger.setLevel(cls._getLsstLogLevel(level))
318 logging.getLogger(component or None).setLevel(cls._getPyLogLevel(level))
320 @staticmethod
321 def _getPyLogLevel(level):
322 """Get the numeric value for the given log level name.
324 Parameters
325 ----------
326 level : `str`
327 One of the python `logging` log level names.
329 Returns
330 -------
331 numericValue : `int`
332 The python `logging` numeric value for the log level.
333 """
334 if level == "VERBOSE":
335 return VERBOSE
336 elif level == "TRACE":
337 return TRACE
338 return getattr(logging, level, None)
340 @staticmethod
341 def _getLsstLogLevel(level):
342 """Get the numeric value for the given log level name.
344 If `lsst.log` is not setup this function will return `None` regardless
345 of input. `daf_butler` does not directly depend on `lsst.log` and so it
346 will not be setup when `daf_butler` is setup. Packages that depend on
347 `daf_butler` and use `lsst.log` may setup `lsst.log`.
349 Parameters
350 ----------
351 level : `str`
352 One of the python `logging` log level names.
354 Returns
355 -------
356 numericValue : `int` or `None`
357 The `lsst.log` numeric value.
359 Notes
360 -----
361 ``VERBOSE`` and ``TRACE`` logging are not supported by the LSST logger.
362 ``VERBOSE`` will be converted to ``INFO`` and ``TRACE`` will be
363 converted to ``DEBUG``.
364 """
365 if lsstLog is None:
366 return None
367 if level == "VERBOSE":
368 level = "INFO"
369 elif level == "TRACE":
370 level = "DEBUG"
371 pylog_level = CliLog._getPyLogLevel(level)
372 return lsstLog.LevelTranslator.logging2lsstLog(pylog_level)
374 class ComponentSettings:
375 """Container for log level values for a logging component."""
377 def __init__(self, component):
378 self.component = component
379 self.pythonLogLevel = logging.getLogger(component).level
380 self.lsstLogLevel = (
381 lsstLog.Log.getLogger(component or "").getLevel() if lsstLog is not None else None
382 )
383 if self.lsstLogLevel == -1:
384 self.lsstLogLevel = CliLog.defaultLsstLogLevel
386 def __repr__(self):
387 return (
388 f"ComponentSettings(component={self.component}, pythonLogLevel={self.pythonLogLevel}, "
389 f"lsstLogLevel={self.lsstLogLevel})"
390 )
392 @classmethod
393 def _recordComponentSetting(cls, component):
394 """Cache current levels for the given component in the list of
395 component levels."""
396 componentSettings = cls.ComponentSettings(component)
397 cls._componentSettings.append(componentSettings)
399 @classmethod
400 def replayConfigState(cls, configState):
401 """Re-create configuration using configuration state recorded earlier.
403 Parameters
404 ----------
405 configState : `list` of `tuple`
406 Tuples contain a method as first item and arguments for the method,
407 in the same format as ``cls.configState``.
408 """
409 if cls._initialized or cls.configState:
410 # Already initialized, do not touch anything.
411 log = logging.getLogger(__name__)
412 log.warning("Log is already initialized, will not replay configuration.")
413 return
415 # execute each one in order
416 for call in configState:
417 method, *args = call
418 method(*args)