Coverage for geometric_kernels/_logging.py: 73%

22 statements  

« prev     ^ index     » next       coverage.py v7.11.3, created at 2025-11-16 21:43 +0000

1"""Setup logging""" 

2 

3import logging 

4 

5 

6class DisableLogging: 

7 """ 

8 Temporarily disable logging (except for the `CRITICAL` level messages). 

9 Adapted from https://stackoverflow.com/a/20251235. Use as 

10 

11 .. code-block:: python 

12 

13 with DisableLogging(): 

14 do_your_stuff 

15 """ 

16 

17 def __enter__(self): 

18 logging.disable(logging.CRITICAL) 

19 

20 def __exit__(self, exit_type, exit_value, exit_traceback): 

21 logging.disable(logging.NOTSET) 

22 

23 

24class FirstPartFilter(logging.Filter): 

25 """ 

26 A filter that provides the `name_first` variable for formatting. For a 

27 logger called "aaa.bbb.ccc", name_first="aaa". 

28 Adapted from https://stackoverflow.com/a/46961676. 

29 """ 

30 

31 def filter(self, record): 

32 record.name_first = record.name.rsplit(".", 1)[0] 

33 return True 

34 

35 

36class NoUsingBackendFilter(logging.Filter): 

37 """ 

38 A filter that removes the "Using ... backend" log record of geomstats. 

39 """ 

40 

41 def filter(self, record): 

42 msg = record.getMessage() 

43 # TODO: when geomstats implements better logging, add 

44 # msg.name_first == "geomstats" 

45 # as the third condition for filtering. 

46 return not (msg.startswith("Using ") and msg.endswith(" backend")) 

47 

48 

49root_handler = logging.StreamHandler() 

50root_handler.addFilter(FirstPartFilter()) 

51root_handler.addFilter(NoUsingBackendFilter()) 

52formatter = logging.Formatter("%(levelname)s (%(name_first)s): %(message)s") 

53root_handler.setFormatter(formatter) 

54# Note: using baseConfig allows the "outermost" code to define the logging 

55# policy: once one baseConfig has been called, each subsequent basicConfig 

56# call is ignored. That is unless force=True parameter is set, which, 

57# hopefully, is only done sparingly and with good reason. 

58logging.basicConfig(handlers=[root_handler]) 

59 

60logger = logging.getLogger("geometric_kernels") 

61logger.setLevel(logging.INFO) # can be easily changed by downstream code