Passed
Push — master ( 7604ab...98ccbc )
by Konstantin
02:32
created

ocrd.cli.log   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 9
eloc 31
dl 0
loc 49
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A LogCtx.__init__() 0 2 1
A LogCtx.log() 0 3 1

2 Functions

Rating   Name   Duplication   Size   Complexity  
A log_cli() 0 9 1
B _bind_log_command() 0 13 6
1
"""
2
OCR-D CLI: Logging
3
4
.. click:: ocrd.cli.log:log_cli
5
    :prog: ocrd log
6
    :nested: full
7
"""
8
import click
9
from ocrd_utils import initLogging, getLogger, getLevelName
10
import logging
11
12
class LogCtx():
13
14
    def __init__(self, name):
15
        self.name = name
16
17
    def log(self, lvl, *args, **kwargs):
18
        logger = getLogger(self.name)
19
        logger.log(getLevelName(lvl), *args, **kwargs)
20
21
pass_log = click.make_pass_decorator(LogCtx)
22
23
@click.group("log")
24
@click.option('-n', '--name', envvar='OCRD_TOOL_NAME', default='', metavar='LOGGER_NAME', help='Name of the logger', show_default=True)
25
@click.pass_context
26
def log_cli(ctx, name, *args, **kwargs):
27
    """
28
    Logging
29
    """
30
    initLogging()
31
    ctx.obj = LogCtx(name)
32
33
def _bind_log_command(lvl):
34
    @click.argument('msgs', nargs=-1)
35
    @pass_log
36
    def _log_wrapper(ctx, msgs):
37
        if not msgs:
38
            ctx.log(lvl.upper(), '')
39
        elif len(msgs) == 1 and msgs[0] == '-':
40
            for stdin_line in click.get_text_stream('stdin'):
41
                ctx.log(lvl.upper(), stdin_line.rstrip('\n'))
42
        else:
43
            msg = list(msgs) if '%s' in msgs[0] else ' '.join([x.replace('%', '%%') for x in msgs])
44
            ctx.log(lvl.upper(), msg)
45
    return _log_wrapper
46
47
for _lvl in ['trace', 'debug', 'info', 'warning', 'error', 'critical']:
48
    log_cli.command(_lvl, help="Log a %s message" % _lvl.upper())(_bind_log_command(_lvl))
49