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

er()   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
_initialized_flag = False
50
51
_ocrdLevel2pythonLevel = {
52
    'TRACE': 'DEBUG',
53
    'OFF': 'CRITICAL',
54
    'FATAL': 'ERROR',
55
}
56
57
def tf_disable_interactive_logs():
58
    try:
59
        from os import environ
60
        # This env variable must be set before importing from Keras
61
        environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
62
        from tensorflow.keras.utils import disable_interactive_logging
63
        # Enabled interactive logging throws an exception
64
        # due to a call of sys.stdout.flush()
65
        disable_interactive_logging()
66
    except ImportError:
67
        # Nothing should be handled here if TF is not available
68
        pass
69
70
def getLevelName(lvl):
71
    """
72
    Get (string) python logging level for (string) spec-defined log level name.
73
    """
74
    lvl = _ocrdLevel2pythonLevel.get(lvl, lvl)
75
    return logging.getLevelName(lvl)
76
77
def getLogger(*args, **kwargs):
78
    """
79
    Wrapper around ``logging.getLogger`` that alls :py:func:`initLogging` if
80
    that wasn't explicitly called before.
81
    """
82
    if not _initialized_flag:
83
        initLogging()
84
    logger = logging.getLogger(*args, **kwargs)
85
    return logger
86
87
def setOverrideLogLevel(lvl, silent=False):
88
    """
89
    Override the output log level of the handlers attached to the ``ocrd`` logger.
90
91
    Args:
92
        lvl (string): Log level name.
93
        silent (boolean): Whether to log the override call
94
    """
95
    if not _initialized_flag:
96
        initLogging()
97
    ocrd_logger = logging.getLogger('ocrd')
98
99
    if lvl is None:
100
        if not silent:
101
            ocrd_logger.info('Reset log level override')
102
        ocrd_logger.setLevel(logging.NOTSET)
103
    else:
104
        if not silent:
105
            ocrd_logger.info('Overriding log level globally to %s', lvl)
106
        ocrd_logger.setLevel(lvl)
107
108
def initLogging(builtin_only=False, basic_config=True, force_reinit=False):
109
    """
110
    Reset ``ocrd`` logger, read logging configuration if exists, otherwise use basicConfig
111
112
    initLogging is to be called by OCR-D/core once, i.e.
113
        -  for the ``ocrd`` CLI
114
        -  for the processor wrapper methods
115
116
    Other processes that use OCR-D/core as a library can, but do not have to, use this functionality.
117
118
    Keyword Args:
119
        - basic_config (bool, False): Whether to attach the handler to the
120
                                      root logger instead of just the ``ocrd`` logger
121
                                      like ``logging.basicConfig`` does.
122
        - builtin_only (bool, False): Whether to search for logging configuration
123
                                      on-disk (``False``) or only use the
124
                                      hard-coded config (``True``). For testing
125
        - force_reinit (bool, False): Whether to ignore the module-level
126
                                      ``_initialized_flag``. For testing only.
127
    """
128
    global _initialized_flag
129
    if _initialized_flag and not force_reinit:
130
        return
131
132
    # https://docs.python.org/3/library/logging.html#logging.disable
133
    # If logging.disable(logging.NOTSET) is called, it effectively removes this
134
    # overriding level, so that logging output again depends on the effective
135
    # levels of individual loggers.
136
    logging.disable(logging.NOTSET)
137
138
    # remove all handlers for the ocrd logger
139
    for handler in logging.getLogger('ocrd').handlers[:]:
140
        logging.getLogger('ocrd').removeHandler(handler)
141
142
    config_file = None
143
    if not builtin_only:
144
        CONFIG_PATHS = [
145
            Path.cwd(),
146
            Path.home(),
147
            Path('/etc'),
148
        ]
149
        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...
150
                in [p / 'ocrd_logging.conf' for p in CONFIG_PATHS] \
151
                if f.exists()),
152
                None)
153
    if config_file:
154
        logging.config.fileConfig(config_file)
155
        logging.getLogger('ocrd.logging').debug("Picked up logging config at %s", config_file)
156
    else:
157
        # Default logging config
158
        ocrd_handler = logging.StreamHandler(stream=sys.stderr)
159
        ocrd_handler.setFormatter(logging.Formatter(fmt=LOG_FORMAT, datefmt=LOG_TIMEFMT))
160
        if basic_config:
161
            logging.getLogger('').addHandler(ocrd_handler)
162
        else:
163
            logging.getLogger('ocrd').addHandler(ocrd_handler)
164
        logging.getLogger('ocrd').setLevel('INFO')
165
        #  logging.getLogger('ocrd.resolver').setLevel(logging.INFO)
166
        #  logging.getLogger('ocrd.resolver.download_to_directory').setLevel(logging.INFO)
167
        #  logging.getLogger('ocrd.resolver.add_files_to_mets').setLevel(logging.INFO)
168
        logging.getLogger('PIL').setLevel(logging.INFO)
169
        # To cut back on the `Self-intersection at or near point` INFO messages
170
        logging.getLogger('shapely.geos').setLevel(logging.ERROR)
171
        logging.getLogger('tensorflow').setLevel(logging.ERROR)
172
173
    _initialized_flag = True
174
175
def disableLogging():
176
    """
177
    Disables all logging of the ``ocrd`` logger and descendants
178
    """
179
    global _initialized_flag # pylint: disable=global-statement
180
    if _initialized_flag:
181
        logging.getLogger('ocrd.logging').debug("Disabling logging")
182
    _initialized_flag = False
183
    # logging.basicConfig(level=logging.CRITICAL)
184
    # logging.disable(logging.ERROR)
185
    # remove all handlers for the ocrd logger
186
    for handler in logging.getLogger('ocrd').handlers[:]:
187
        logging.getLogger('ocrd').removeHandler(handler)
188
189
# Initializing stream handlers at module level
190
# would cause message output in all runtime contexts,
191
# including those which are already run for std output
192
# (--dump-json, --version, ocrd-tool, bashlib etc).
193
# So this needs to be an opt-in from the CLIs/decorators:
194
#initLogging()
195
# Also, we even have to block log output for libraries
196
# (like matplotlib/tensorflow) which set up logging
197
# themselves already:
198
disableLogging()
199