Passed
Pull Request — master (#1080)
by Konstantin
03:34
created

PropagationShyLogger.removeHandler()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nop 2
1
"""
2
Logging setup
3
4
By default: Log with lastResort logger, usually STDERR.
5
6
Logging can be overridden either programmatically in code using the library or by creating one or more of
7
8
- /etc/ocrd_logging.py
9
- $HOME/ocrd_logging.py
10
- $PWD/ocrd_logging.py
11
12
These files will be executed in the context of ocrd/ocrd_logging.py, with `logging` global set.
13
14
Changes as of 2023-08-20:
15
16
    - Try to be less intrusive with OCR-D specific logging conventions to
17
      make it easier and less surprising to define logging behavior when
18
      using OCR-D/core as a library
19
    - Change setOverrideLogLevel to only override the log level of the ``ocrd``
20
      logger and its descendants
21
    - initLogging will set exactly one handler, for the root logger or for the
22
      ``ocrd`` logger.
23
    - Child loggers should propagate to the ancestor logging (default
24
      behavior of the logging library - no more PropagationShyLogger)
25
    - disableLogging only removes any handlers from the ``ocrd`` logger
26
"""
27
# pylint: disable=no-member
28
29
from __future__ import absolute_import
30
31
from traceback import format_stack
32
33
import logging
34
import logging.config
35
from pathlib import Path
36
import sys
37
38
from .constants import LOG_FORMAT, LOG_TIMEFMT
39
40
__all__ = [
41
    'disableLogging',
42
    'getLevelName',
43
    'getLogger',
44
    'initLogging',
45
    'logging',
46
    'setOverrideLogLevel',
47
]
48
49
LOGGING_DEFAULTS = {
50
    'ocrd': logging.INFO,
51
    'ocrd_models': logging.INFO,
52
    'ocrd_utils': logging.INFO,
53
    'ocrd_network': logging.INFO,
54
    'ocrd_exif': logging.INFO,
55
    # 'ocrd.resolver': logging.INFO,
56
    # 'ocrd.resolver.download_to_directory': logging.INFO,
57
    # 'ocrd.resolver.add_files_to_mets': logging.INFO,
58
    # To cut back on the `Self-intersection at or near point` INFO messages
59
    'shapely.geos': logging.ERROR,
60
    'tensorflow': logging.ERROR,
61
    'PIL': logging.INFO,
62
}
63
64
_initialized_flag = False
65
66
_ocrdLevel2pythonLevel = {
67
    'TRACE': 'DEBUG',
68
    'OFF': 'CRITICAL',
69
    'FATAL': 'ERROR',
70
}
71
72
def tf_disable_interactive_logs():
73
    try:
74
        from os import environ
75
        # This env variable must be set before importing from Keras
76
        environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
77
        from tensorflow.keras.utils import disable_interactive_logging
78
        # Enabled interactive logging throws an exception
79
        # due to a call of sys.stdout.flush()
80
        disable_interactive_logging()
81
    except ImportError:
82
        # Nothing should be handled here if TF is not available
83
        pass
84
85
def getLevelName(lvl):
86
    """
87
    Get (string) python logging level for (string) spec-defined log level name.
88
    """
89
    lvl = _ocrdLevel2pythonLevel.get(lvl, lvl)
90
    return logging.getLevelName(lvl)
91
92
def getLogger(*args, **kwargs):
93
    """
94
    Wrapper around ``logging.getLogger`` that alls :py:func:`initLogging` if
95
    that wasn't explicitly called before.
96
    """
97
    if not _initialized_flag:
98
        initLogging()
99
    logger = logging.getLogger(*args, **kwargs)
100
    return logger
101
102
def setOverrideLogLevel(lvl, silent=True):
103
    """
104
    Override the output log level of the handlers attached to the ``ocrd`` logger.
105
106
    Args:
107
        lvl (string): Log level name.
108
        silent (boolean): Whether to log the override call
109
    """
110
    if not _initialized_flag:
111
        initLogging()
112
    ocrd_logger = logging.getLogger('ocrd')
113
114
    if lvl is None:
115
        if not silent:
116
            ocrd_logger.info('Reset log level override')
117
        ocrd_logger.setLevel(logging.NOTSET)
118
    else:
119
        if not silent:
120
            ocrd_logger.info('Overriding ocrd log level to %s', lvl)
121
        ocrd_logger.setLevel(lvl)
122
123
def initLogging(builtin_only=False, force_reinit=False):
124
    """
125
    Reset ``ocrd`` logger, read logging configuration if exists, otherwise use basicConfig
126
127
    initLogging is to be called by OCR-D/core once, i.e.
128
        -  for the ``ocrd`` CLI
129
        -  for the processor wrapper methods
130
131
    Other processes that use OCR-D/core as a library can, but do not have to, use this functionality.
132
133
    Keyword Args:
134
        - builtin_only (bool, False): Whether to search for logging configuration
135
                                      on-disk (``False``) or only use the
136
                                      hard-coded config (``True``). For testing
137
        - force_reinit (bool, False): Whether to ignore the module-level
138
                                      ``_initialized_flag``. For testing only.
139
    """
140
    global _initialized_flag
141
    if _initialized_flag and not force_reinit:
142
        return
143
    # disableLogging()
144
145
    # https://docs.python.org/3/library/logging.html#logging.disable
146
    # If logging.disable(logging.NOTSET) is called, it effectively removes this
147
    # overriding level, so that logging output again depends on the effective
148
    # levels of individual loggers.
149
    logging.disable(logging.NOTSET)
150
151
    # remove all handlers for the ocrd logger
152
    for handler in logging.getLogger('ocrd').handlers[:]:
153
        logging.getLogger('ocrd').removeHandler(handler)
154
155
    config_file = None
156
    if not builtin_only:
157
        CONFIG_PATHS = [
158
            Path.cwd(),
159
            Path.home(),
160
            Path('/etc'),
161
        ]
162
        config_file = next((f for f \
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable f does not seem to be defined.
Loading history...
163
                in [p / 'ocrd_logging.conf' for p in CONFIG_PATHS] \
164
                if f.exists()),
165
                None)
166
    if config_file:
167
        logging.config.fileConfig(config_file)
168
        logging.getLogger('ocrd.logging').debug("Picked up logging config at %s", config_file)
169
    else:
170
        # Default logging config
171
        ocrd_handler = logging.StreamHandler(stream=sys.stderr)
172
        ocrd_handler.setFormatter(logging.Formatter(fmt=LOG_FORMAT, datefmt=LOG_TIMEFMT))
173
        ocrd_handler.setLevel(logging.DEBUG)
174
        logging.getLogger('ocrd').addHandler(ocrd_handler)
175
        for logger_name, logger_level in LOGGING_DEFAULTS.items():
176
            logging.getLogger(logger_name).setLevel(logger_level)
177
178
    _initialized_flag = True
179
180
def disableLogging(silent=True):
181
    """
182
    Disables all logging of the ``ocrd`` logger and descendants
183
184
    Keyword Args:
185
        silent (bool, True): Whether to log the call to disableLogging
186
    """
187
    global _initialized_flag # pylint: disable=global-statement
188
    if _initialized_flag and not silent:
189
        logging.getLogger('ocrd.logging').debug("Disabling logging")
190
    _initialized_flag = False
191
    # logging.basicConfig(level=logging.CRITICAL)
192
    # logging.disable(logging.ERROR)
193
    # remove all handlers for the ocrd logger
194
    for handler in logging.getLogger('ocrd').handlers[:]:
195
        logging.getLogger('ocrd').removeHandler(handler)
196
    for logger_name in LOGGING_DEFAULTS:
197
        logging.getLogger(logger_name).setLevel(logging.NOTSET)
198
199
# Initializing stream handlers at module level
200
# would cause message output in all runtime contexts,
201
# including those which are already run for std output
202
# (--dump-json, --version, ocrd-tool, bashlib etc).
203
# So this needs to be an opt-in from the CLIs/decorators:
204
#initLogging()
205
# Also, we even have to block log output for libraries
206
# (like matplotlib/tensorflow) which set up logging
207
# themselves already:
208
disableLogging()
209