Skip to content

Commit b189423

Browse files
committed
feat: type hinting in gLogger
1 parent 42155fd commit b189423

File tree

3 files changed

+60
-52
lines changed

3 files changed

+60
-52
lines changed

src/DIRAC/FrameworkSystem/private/standardLogging/LogLevels.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
LogLevels wrapper
33
"""
4+
from __future__ import annotations
45
from enum import IntEnum
56
import logging
67

@@ -53,7 +54,7 @@ class LogLevels:
5354
}
5455

5556
@classmethod
56-
def getLevelValue(cls, sName):
57+
def getLevelValue(cls, sName: str) -> int | None:
5758
"""
5859
Get a level value from a level name.
5960
We could use logging.getLevelName() to get the level value but it is less simple.
@@ -64,7 +65,7 @@ def getLevelValue(cls, sName):
6465
return cls.__levelDict.get(sName.upper())
6566

6667
@classmethod
67-
def getLevel(cls, level):
68+
def getLevel(cls, level: int) -> str | None:
6869
"""
6970
Get a level name from a level value.
7071
We could use logging.getLevelName() to get the level value but it is less simple.
@@ -78,14 +79,14 @@ def getLevel(cls, level):
7879
return None
7980

8081
@classmethod
81-
def getLevelNames(cls):
82+
def getLevelNames(cls) -> list[str]:
8283
"""
8384
:return: all level names available in the wrapper
8485
"""
8586
return list(cls.__levelDict)
8687

8788
@classmethod
88-
def getLevels(cls):
89+
def getLevels(cls) -> dict[str, int]:
8990
"""
9091
:return: the level dictionary. Must no be redefined
9192
"""

src/DIRAC/FrameworkSystem/private/standardLogging/Logging.py

Lines changed: 47 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
Logging
33
"""
4+
from __future__ import annotations
45
import logging
56
import os
67

@@ -29,7 +30,7 @@ class Logging:
2930
# lock the configuration of the Logging
3031
_lockConfig = _lockRing.getLock("config")
3132

32-
def __init__(self, father=None, name=""):
33+
def __init__(self, father: Logging | None = None, name: str = ""):
3334
"""
3435
Initialization of the Logging object. By default, 'name' is empty,
3536
because getChild only accepts string and the first empty string corresponds to the root logger.
@@ -93,15 +94,15 @@ def __init__(self, father=None, name=""):
9394
# lockObjectLoader to protect the ObjectLoader singleton
9495
self._lockObjectLoader = self._lockRing.getLock("objectLoader")
9596

96-
def showHeaders(self, yesno=True):
97+
def showHeaders(self, yesno: bool = True):
9798
"""
9899
Depending on the value, display or not the prefix of the message.
99100
100101
:param bool yesno: determine the log record format
101102
"""
102103
self._setOption("headerIsShown", yesno)
103104

104-
def showThreadIDs(self, yesno=True):
105+
def showThreadIDs(self, yesno: bool = True):
105106
"""
106107
Depending on the value, display or not the thread ID.
107108
Make sure to enable the headers: showHeaders(True) before
@@ -110,7 +111,7 @@ def showThreadIDs(self, yesno=True):
110111
"""
111112
self._setOption("threadIDIsShown", yesno)
112113

113-
def showTimeStamps(self, yesno=True):
114+
def showTimeStamps(self, yesno: bool = True):
114115
"""
115116
Depending on the value, display or not the timestamp of the message.
116117
Make sure to enable the headers: showHeaders(True) before
@@ -119,7 +120,7 @@ def showTimeStamps(self, yesno=True):
119120
"""
120121
self._setOption("timeStampIsShown", yesno)
121122

122-
def showContexts(self, yesno=True):
123+
def showContexts(self, yesno: bool = True):
123124
"""
124125
Depending on the value, display or not the context of the message.
125126
Make sure to enable the headers: showHeaders(True) before
@@ -128,7 +129,7 @@ def showContexts(self, yesno=True):
128129
"""
129130
self._setOption("contextIsShown", yesno)
130131

131-
def _setOption(self, optionName, value, directCall=True):
132+
def _setOption(self, optionName: str, value: bool, directCall: bool = True):
132133
"""
133134
Depending on the value, modify the value of the option and propagate the option to the children.
134135
The options of the children will be updated if they were not modified before by a developer.
@@ -155,7 +156,9 @@ def _setOption(self, optionName, value, directCall=True):
155156
finally:
156157
self._lockOptions.release()
157158

158-
def registerBackend(self, desiredBackend, backendOptions=None, backendFilters=None):
159+
def registerBackend(
160+
self, desiredBackend: str, backendOptions: dict | None = None, backendFilters: dict | None = None
161+
) -> bool:
159162
"""
160163
Attach a backend to the Logging object.
161164
Convert backend name to backend class name to a Backend object and add it to the Logging object
@@ -184,7 +187,7 @@ def registerBackend(self, desiredBackend, backendOptions=None, backendFilters=No
184187
self._addBackend(_class["Value"], backendOptions, filterInstances)
185188
return True
186189

187-
def _addBackend(self, backendType, backendOptions=None, backendFilters=None):
190+
def _addBackend(self, backendType, backendOptions: dict | None = None, backendFilters: list | None = None):
188191
"""
189192
Attach a Backend object to the Logging object.
190193
@@ -205,7 +208,7 @@ def _addBackend(self, backendType, backendOptions=None, backendFilters=None):
205208
self._lockLevel.release()
206209
self._lockOptions.release()
207210

208-
def _generateFilter(self, filterType, filterOptions=None):
211+
def _generateFilter(self, filterType: str, filterOptions: dict | None = None):
209212
"""
210213
Create a filter and add it to the handler of the backend.
211214
@@ -218,7 +221,7 @@ def _generateFilter(self, filterType, filterOptions=None):
218221
return None
219222
return _class["Value"](filterOptions)
220223

221-
def setLevel(self, levelName):
224+
def setLevel(self, levelName: str) -> bool:
222225
"""
223226
Check if the level name exists and set it.
224227
@@ -234,13 +237,13 @@ def setLevel(self, levelName):
234237
return True
235238
return False
236239

237-
def getLevel(self):
240+
def getLevel(self) -> str:
238241
"""
239242
:return: the name of the level
240243
"""
241244
return LogLevels.getLevel(self._logger.getEffectiveLevel())
242245

243-
def shown(self, levelName):
246+
def shown(self, levelName: str) -> bool:
244247
"""
245248
Determine whether messages with a certain level will be displayed.
246249
@@ -259,19 +262,19 @@ def shown(self, levelName):
259262
self._lockLevel.release()
260263

261264
@classmethod
262-
def getName(cls):
265+
def getName(cls) -> str:
263266
"""
264267
:return: "system name/component name"
265268
"""
266269
return cls._componentName
267270

268-
def getSubName(self):
271+
def getSubName(self) -> str:
269272
"""
270273
:return: the name of the logger
271274
"""
272275
return self.name
273276

274-
def getDisplayOptions(self):
277+
def getDisplayOptions(self) -> dict[str, bool]:
275278
"""
276279
:return: the dictionary of the display options and their values. Must not be redefined
277280
"""
@@ -284,7 +287,7 @@ def getDisplayOptions(self):
284287
finally:
285288
self._lockOptions.release()
286289

287-
def __loadLogClass(self, modulePath):
290+
def __loadLogClass(self, modulePath: str):
288291
"""Load class thread-safe."""
289292
# import ObjectLoader here to avoid a dependancy loop
290293
from DIRAC.Core.Utilities.ObjectLoader import ObjectLoader
@@ -300,69 +303,71 @@ def __loadLogClass(self, modulePath):
300303
self._lockObjectLoader.release()
301304

302305
@staticmethod
303-
def getAllPossibleLevels():
306+
def getAllPossibleLevels() -> list[str]:
304307
"""
305308
:return: a list of all levels available
306309
"""
307310
return LogLevels.getLevelNames()
308311

309-
def always(self, sMsg, sVarMsg=""):
312+
def always(self, sMsg: str, sVarMsg: str = "") -> bool:
310313
"""
311314
Always level
312315
"""
313316
return self._createLogRecord(LogLevels.ALWAYS, sMsg, sVarMsg)
314317

315-
def notice(self, sMsg, sVarMsg=""):
318+
def notice(self, sMsg: str, sVarMsg: str = "") -> bool:
316319
"""
317320
Notice level
318321
"""
319322
return self._createLogRecord(LogLevels.NOTICE, sMsg, sVarMsg)
320323

321-
def info(self, sMsg, sVarMsg=""):
324+
def info(self, sMsg: str, sVarMsg: str = "") -> bool:
322325
"""
323326
Info level
324327
"""
325328
return self._createLogRecord(LogLevels.INFO, sMsg, sVarMsg)
326329

327-
def verbose(self, sMsg, sVarMsg=""):
330+
def verbose(self, sMsg: str, sVarMsg: str = "") -> bool:
328331
"""
329332
Verbose level
330333
"""
331334
return self._createLogRecord(LogLevels.VERBOSE, sMsg, sVarMsg)
332335

333-
def debug(self, sMsg, sVarMsg=""):
336+
def debug(self, sMsg: str, sVarMsg: str = "") -> bool:
334337
"""
335338
Debug level
336339
"""
337340
return self._createLogRecord(LogLevels.DEBUG, sMsg, sVarMsg)
338341

339-
def warn(self, sMsg, sVarMsg=""):
342+
def warn(self, sMsg: str, sVarMsg: str = "") -> bool:
340343
"""
341344
Warn
342345
"""
343346
return self._createLogRecord(LogLevels.WARN, sMsg, sVarMsg)
344347

345-
def error(self, sMsg, sVarMsg=""):
348+
def error(self, sMsg: str, sVarMsg: str = "") -> bool:
346349
"""
347350
Error level
348351
"""
349352
return self._createLogRecord(LogLevels.ERROR, sMsg, sVarMsg)
350353

351-
def exception(self, sMsg="", sVarMsg="", lException=False, lExcInfo=False):
354+
def exception(self, sMsg: str = "", sVarMsg: str = "", lException: bool = False, lExcInfo: bool = False) -> bool:
352355
"""
353356
Exception level
354357
"""
355358
_ = lException # Make pylint happy
356359
_ = lExcInfo
357360
return self._createLogRecord(LogLevels.ERROR, sMsg, sVarMsg, exc_info=True)
358361

359-
def fatal(self, sMsg, sVarMsg=""):
362+
def fatal(self, sMsg: str, sVarMsg: str = "") -> bool:
360363
"""
361364
Fatal level
362365
"""
363366
return self._createLogRecord(LogLevels.FATAL, sMsg, sVarMsg)
364367

365-
def _createLogRecord(self, level, sMsg, sVarMsg, exc_info=False, local_context=None):
368+
def _createLogRecord(
369+
self, level: int, sMsg: str, sVarMsg: str, exc_info: bool = False, local_context: dict | None = None
370+
) -> bool:
366371
"""
367372
Create a log record according to the level of the message.
368373
@@ -410,15 +415,15 @@ def _createLogRecord(self, level, sMsg, sVarMsg, exc_info=False, local_context=N
410415
finally:
411416
self._lockLevel.release()
412417

413-
def showStack(self):
418+
def showStack(self) -> bool:
414419
"""
415420
Display a debug message without any content.
416421
417422
:return: boolean, True if the message is sent, else False
418423
"""
419424
return self.debug("")
420425

421-
def getSubLogger(self, subName):
426+
def getSubLogger(self, subName: str) -> Logging:
422427
"""
423428
Create a new Logging object, child of this Logging, if it does not exists.
424429
@@ -459,7 +464,7 @@ class LocalSubLogger:
459464
(see https://github.com/DIRACGrid/DIRAC/issues/5280)
460465
"""
461466

462-
def __init__(self, logger, extra):
467+
def __init__(self, logger: Logging, extra: dict):
463468
"""
464469
:param logger: :py:class:`Logging` object on which to be based
465470
:param extra: dictionary of extra information to be passed
@@ -468,63 +473,65 @@ def __init__(self, logger, extra):
468473
self.logger = logger
469474
self.extra = extra
470475

471-
def always(self, sMsg, sVarMsg=""):
476+
def always(self, sMsg: str, sVarMsg: str = "") -> bool:
472477
"""
473478
Always level
474479
"""
475480
return self.logger._createLogRecord( # pylint: disable=protected-access
476481
LogLevels.ALWAYS, sMsg, sVarMsg, local_context=self.extra
477482
)
478483

479-
def notice(self, sMsg, sVarMsg=""):
484+
def notice(self, sMsg: str, sVarMsg: str = "") -> bool:
480485
"""
481486
Notice level
482487
"""
483488
return self.logger._createLogRecord( # pylint: disable=protected-access
484489
LogLevels.NOTICE, sMsg, sVarMsg, local_context=self.extra
485490
)
486491

487-
def info(self, sMsg, sVarMsg=""):
492+
def info(self, sMsg: str, sVarMsg: str = "") -> bool:
488493
"""
489494
Info level
490495
"""
491496
return self.logger._createLogRecord( # pylint: disable=protected-access
492497
LogLevels.INFO, sMsg, sVarMsg, local_context=self.extra
493498
)
494499

495-
def verbose(self, sMsg, sVarMsg=""):
500+
def verbose(self, sMsg: str, sVarMsg: str = "") -> bool:
496501
"""
497502
Verbose level
498503
"""
499504
return self.logger._createLogRecord( # pylint: disable=protected-access
500505
LogLevels.VERBOSE, sMsg, sVarMsg, local_context=self.extra
501506
)
502507

503-
def debug(self, sMsg, sVarMsg=""):
508+
def debug(self, sMsg: str, sVarMsg: str = "") -> bool:
504509
"""
505510
Debug level
506511
"""
507512
return self.logger._createLogRecord( # pylint: disable=protected-access
508513
LogLevels.DEBUG, sMsg, sVarMsg, local_context=self.extra
509514
)
510515

511-
def warn(self, sMsg, sVarMsg=""):
516+
def warn(self, sMsg: str, sVarMsg: str = "") -> bool:
512517
"""
513518
Warn
514519
"""
515520
return self.logger._createLogRecord( # pylint: disable=protected-access
516521
LogLevels.WARN, sMsg, sVarMsg, local_context=self.extra
517522
)
518523

519-
def error(self, sMsg, sVarMsg=""):
524+
def error(self, sMsg: str, sVarMsg: str = "") -> bool:
520525
"""
521526
Error level
522527
"""
523528
return self.logger._createLogRecord( # pylint: disable=protected-access
524529
LogLevels.ERROR, sMsg, sVarMsg, local_context=self.extra
525530
)
526531

527-
def exception(self, sMsg="", sVarMsg="", lException=False, lExcInfo=False):
532+
def exception(
533+
self, sMsg: str = "", sVarMsg: str = "", lException: bool = False, lExcInfo: bool = False
534+
) -> bool:
528535
"""
529536
Exception level
530537
"""
@@ -534,15 +541,15 @@ def exception(self, sMsg="", sVarMsg="", lException=False, lExcInfo=False):
534541
LogLevels.ERROR, sMsg, sVarMsg, exc_info=True, local_context=self.extra
535542
)
536543

537-
def fatal(self, sMsg, sVarMsg=""):
544+
def fatal(self, sMsg: str, sVarMsg: str = "") -> bool:
538545
"""
539546
Fatal level
540547
"""
541548
return self.logger._createLogRecord( # pylint: disable=protected-access
542549
LogLevels.FATAL, sMsg, sVarMsg, local_context=self.extra
543550
)
544551

545-
def getLocalSubLogger(self, subName):
552+
def getLocalSubLogger(self, subName: str) -> Logging.LocalSubLogger:
546553
"""
547554
Create a subLogger which is meant to have very short lifetime,
548555
(e.g. when you want to add the jobID in the name)

0 commit comments

Comments
 (0)