Coverage for python/lsst/utils/logging.py: 56%

Shortcuts on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

103 statements  

1# This file is part of utils. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (https://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# Use of this source code is governed by a 3-clause BSD-style 

10# license that can be found in the LICENSE file. 

11 

12from __future__ import annotations 

13 

14__all__ = ("TRACE", "VERBOSE", "getLogger", "LsstLogAdapter", "trace_set_at") 

15 

16import logging 

17from logging import LoggerAdapter 

18from deprecated.sphinx import deprecated 

19from contextlib import contextmanager 

20 

21from typing import ( 

22 Any, 

23 Generator, 

24 List, 

25 Optional, 

26 Union, 

27) 

28 

29try: 

30 import lsst.log.utils as logUtils 

31except ImportError: 

32 logUtils = None 

33 

34# log level for trace (verbose debug). 

35TRACE = 5 

36logging.addLevelName(TRACE, "TRACE") 

37 

38# Verbose logging is midway between INFO and DEBUG. 

39VERBOSE = (logging.INFO + logging.DEBUG) // 2 

40logging.addLevelName(VERBOSE, "VERBOSE") 

41 

42 

43def trace_set_at(name: str, number: int) -> None: 

44 """Adjusts logging level to display messages with the trace number being 

45 less than or equal to the provided value. 

46 

47 Parameters 

48 ---------- 

49 name : `str` 

50 Name of the logger. 

51 number : `int` 

52 The trace number threshold for display. 

53 

54 Notes 

55 ----- 

56 Loggers ``TRACE0.`` to ``TRACE5.`` are set. All loggers above 

57 the specified threshold are set to ``INFO`` and those below the threshold 

58 are set to ``DEBUG``. The expectation is that ``TRACE`` loggers only 

59 issue ``DEBUG`` log messages. 

60 

61 Examples 

62 -------- 

63 

64 .. code-block:: python 

65 

66 lsst.utils.logging.trace_set_at("lsst.afw", 3) 

67 

68 This will set loggers ``TRACE0.lsst.afw`` to ``TRACE3.lsst.afw`` to 

69 ``DEBUG`` and ``TRACE4.lsst.afw`` and ``TRACE5.lsst.afw`` to ``INFO``. 

70 

71 Notes 

72 ----- 

73 If ``lsst.log`` is installed, this function will also call 

74 `lsst.log.utils.traceSetAt` to ensure that non-Python loggers are 

75 also configured correctly. 

76 """ 

77 for i in range(6): 

78 level = logging.INFO if i > number else logging.DEBUG 

79 log_name = f"TRACE{i}.{name}" if name else f"TRACE{i}" 

80 logging.getLogger(log_name).setLevel(level) 

81 

82 # if lsst log is available also set the trace loggers there. 

83 if logUtils is not None: 

84 logUtils.traceSetAt(name, number) 

85 

86 

87class _F: 

88 """ 

89 Format, supporting `str.format()` syntax. 

90 

91 Notes 

92 ----- 

93 This follows the recommendation from 

94 https://docs.python.org/3/howto/logging-cookbook.html#using-custom-message-objects 

95 """ 

96 def __init__(self, fmt: str, /, *args: Any, **kwargs: Any): 

97 self.fmt = fmt 

98 self.args = args 

99 self.kwargs = kwargs 

100 

101 def __str__(self) -> str: 

102 return self.fmt.format(*self.args, **self.kwargs) 

103 

104 

105class LsstLogAdapter(LoggerAdapter): 

106 """A special logging adapter to provide log features for LSST code. 

107 

108 Expected to be instantiated initially by a call to `getLogger()`. 

109 

110 This class provides enhancements over `logging.Logger` that include: 

111 

112 * Methods for issuing trace and verbose level log messages. 

113 * Provision of a context manager to temporarily change the log level. 

114 * Attachment of logging level constants to the class to make it easier 

115 for a Task writer to access a specific log level without having to 

116 know the underlying logger class. 

117 """ 

118 

119 # Store logging constants in the class for convenience. This is not 

120 # something supported by Python loggers but can simplify some 

121 # logic if the logger is available. 

122 CRITICAL = logging.CRITICAL 

123 ERROR = logging.ERROR 

124 DEBUG = logging.DEBUG 

125 INFO = logging.INFO 

126 WARNING = logging.WARNING 

127 

128 # Python supports these but prefers they are not used. 

129 FATAL = logging.FATAL 

130 WARN = logging.WARN 

131 

132 # These are specific to Tasks 

133 TRACE = TRACE 

134 VERBOSE = VERBOSE 

135 

136 @contextmanager 

137 def temporary_log_level(self, level: Union[int, str]) -> Generator: 

138 """A context manager that temporarily sets the level of this logger. 

139 

140 Parameters 

141 ---------- 

142 level : `int` 

143 The new temporary log level. 

144 """ 

145 old = self.level 

146 self.setLevel(level) 

147 try: 

148 yield 

149 finally: 

150 self.setLevel(old) 

151 

152 @property 

153 def level(self) -> int: 

154 """Current level of this logger (``int``).""" 

155 return self.logger.level 

156 

157 def getChild(self, name: str) -> LsstLogAdapter: 

158 """Get the named child logger. 

159 

160 Parameters 

161 ---------- 

162 name : `str` 

163 Name of the child relative to this logger. 

164 

165 Returns 

166 ------- 

167 child : `LsstLogAdapter` 

168 The child logger. 

169 """ 

170 return getLogger(name=name, logger=self.logger) 

171 

172 @deprecated(reason="Use Python Logger compatible isEnabledFor Will be removed after v23.", 

173 version="v23", category=FutureWarning) 

174 def isDebugEnabled(self) -> bool: 

175 return self.isEnabledFor(self.DEBUG) 

176 

177 @deprecated(reason="Use Python Logger compatible 'name' attribute. Will be removed after v23.", 

178 version="v23", category=FutureWarning) 

179 def getName(self) -> str: 

180 return self.name 

181 

182 @deprecated(reason="Use Python Logger compatible .level property. Will be removed after v23.", 

183 version="v23", category=FutureWarning) 

184 def getLevel(self) -> int: 

185 return self.logger.level 

186 

187 def fatal(self, msg: str, *args: Any, **kwargs: Any) -> None: 

188 # Python does not provide this method in LoggerAdapter but does 

189 # not formally deprecated it in favor of critical() either. 

190 # Provide it without deprecation message for consistency with Python. 

191 # stacklevel=5 accounts for the forwarding of LoggerAdapter. 

192 self.critical(msg, *args, **kwargs, stacklevel=4) 

193 

194 def verbose(self, fmt: str, *args: Any, **kwargs: Any) -> None: 

195 """Issue a VERBOSE level log message. 

196 

197 Arguments are as for `logging.info`. 

198 ``VERBOSE`` is between ``DEBUG`` and ``INFO``. 

199 """ 

200 # There is no other way to achieve this other than a special logger 

201 # method. 

202 # Stacklevel is passed in so that the correct line is reported 

203 # in the log record and not this line. 3 is this method, 

204 # 2 is the level from `self.log` and 1 is the log infrastructure 

205 # itself. 

206 self.log(VERBOSE, fmt, *args, stacklevel=3, **kwargs) 

207 

208 def trace(self, fmt: str, *args: Any) -> None: 

209 """Issue a TRACE level log message. 

210 

211 Arguments are as for `logging.info`. 

212 ``TRACE`` is lower than ``DEBUG``. 

213 """ 

214 # There is no other way to achieve this other than a special logger 

215 # method. For stacklevel discussion see `verbose()`. 

216 self.log(TRACE, fmt, *args, stacklevel=3) 

217 

218 @deprecated(reason="Use Python Logger compatible method. Will be removed after v23.", 

219 version="v23", category=FutureWarning) 

220 def tracef(self, fmt: str, *args: Any, **kwargs: Any) -> None: 

221 # Stacklevel is 4 to account for the deprecation wrapper 

222 self.log(TRACE, _F(fmt, *args, **kwargs), stacklevel=4) 

223 

224 @deprecated(reason="Use Python Logger compatible method. Will be removed after v23.", 

225 version="v23", category=FutureWarning) 

226 def debugf(self, fmt: str, *args: Any, **kwargs: Any) -> None: 

227 self.log(logging.DEBUG, _F(fmt, *args, **kwargs), stacklevel=4) 

228 

229 @deprecated(reason="Use Python Logger compatible method. Will be removed after v23.", 

230 version="v23", category=FutureWarning) 

231 def infof(self, fmt: str, *args: Any, **kwargs: Any) -> None: 

232 self.log(logging.INFO, _F(fmt, *args, **kwargs), stacklevel=4) 

233 

234 @deprecated(reason="Use Python Logger compatible method. Will be removed after v23.", 

235 version="v23", category=FutureWarning) 

236 def warnf(self, fmt: str, *args: Any, **kwargs: Any) -> None: 

237 self.log(logging.WARNING, _F(fmt, *args, **kwargs), stacklevel=4) 

238 

239 @deprecated(reason="Use Python Logger compatible method. Will be removed after v23.", 

240 version="v23", category=FutureWarning) 

241 def errorf(self, fmt: str, *args: Any, **kwargs: Any) -> None: 

242 self.log(logging.ERROR, _F(fmt, *args, **kwargs), stacklevel=4) 

243 

244 @deprecated(reason="Use Python Logger compatible method. Will be removed after v23.", 

245 version="v23", category=FutureWarning) 

246 def fatalf(self, fmt: str, *args: Any, **kwargs: Any) -> None: 

247 self.log(logging.CRITICAL, _F(fmt, *args, **kwargs), stacklevel=4) 

248 

249 def setLevel(self, level: Union[int, str]) -> None: 

250 """Set the level for the logger, trapping lsst.log values. 

251 

252 Parameters 

253 ---------- 

254 level : `int` 

255 The level to use. If the level looks too big to be a Python 

256 logging level it is assumed to be a lsst.log level. 

257 """ 

258 if isinstance(level, int) and level > logging.CRITICAL: 

259 self.logger.warning("Attempting to set level to %d -- looks like an lsst.log level so scaling it" 

260 " accordingly.", level) 

261 level //= 1000 

262 

263 self.logger.setLevel(level) 

264 

265 @property 

266 def handlers(self) -> List[logging.Handler]: 

267 """Log handlers associated with this logger.""" 

268 return self.logger.handlers 

269 

270 def addHandler(self, handler: logging.Handler) -> None: 

271 """Add a handler to this logger. 

272 

273 The handler is forwarded to the underlying logger. 

274 """ 

275 self.logger.addHandler(handler) 

276 

277 def removeHandler(self, handler: logging.Handler) -> None: 

278 """Remove the given handler from the underlying logger.""" 

279 self.logger.removeHandler(handler) 

280 

281 

282def getLogger(name: Optional[str] = None, logger: logging.Logger = None) -> LsstLogAdapter: 

283 """Get a logger compatible with LSST usage. 

284 

285 Parameters 

286 ---------- 

287 name : `str`, optional 

288 Name of the logger. Root logger if `None`. 

289 logger : `logging.Logger` or `LsstLogAdapter` 

290 If given the logger is converted to the relevant logger class. 

291 If ``name`` is given the logger is assumed to be a child of the 

292 supplied logger. 

293 

294 Returns 

295 ------- 

296 logger : `LsstLogAdapter` 

297 The relevant logger. 

298 

299 Notes 

300 ----- 

301 A `logging.LoggerAdapter` is used since it is easier to provide a more 

302 uniform interface than when using `logging.setLoggerClass`. An adapter 

303 can be wrapped around the root logger and the `~logging.setLoggerClass` 

304 will return the logger first given that name even if the name was 

305 used before the `Task` was created. 

306 """ 

307 if not logger: 

308 logger = logging.getLogger(name) 

309 elif name: 

310 logger = logger.getChild(name) 

311 return LsstLogAdapter(logger, {}) 

312 

313 

314LsstLoggers = Union[logging.Logger, LsstLogAdapter]