Completed
Push — develop ( b91cd3...d7cca8 )
by Wu
84:13 queued 82:43
created

enable_pretty_logging()   B

Complexity

Conditions 6

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 8.8343

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 18
ccs 8
cts 14
cp 0.5714
cc 6
crap 8.8343
rs 8
1
# -*- coding:utf-8 -*-
2
3 15
import six
4 15
import sys
5 15
import time
6 15
import logging
7
8 15
try:
9 15
    import curses
10
11 15
    assert curses
12
except ImportError:
13
    curses = None
14
15 15
logger = logging.getLogger("WeRoBot")
16
17
18 15
def enable_pretty_logging(logger, level='info'):
19
    """Turns on formatted logging output as configured.
20
    """
21 15
    logger.setLevel(getattr(logging, level.upper()))
22
23 15
    if not logger.handlers:
24
        # Set up color if we are in a tty and curses is installed
25 15
        color = False
26 15
        if curses and sys.stderr.isatty():
27
            try:
28
                curses.setupterm()
29
                if curses.tigetnum("colors") > 0:
30
                    color = True
31
            except:
32
                pass
33 15
        channel = logging.StreamHandler()
34 15
        channel.setFormatter(_LogFormatter(color=color))
35 15
        logger.addHandler(channel)
36
37
38 15
class _LogFormatter(logging.Formatter):
39 15
    def __init__(self, color, *args, **kwargs):
40 15
        logging.Formatter.__init__(self, *args, **kwargs)
41 15
        self._color = color
42 15
        if color:
43
            fg_color = (curses.tigetstr("setaf") or
44
                        curses.tigetstr("setf") or "")
45
            if (3, 0) < sys.version_info < (3, 2, 3):
46
                fg_color = six.text_type(fg_color, "ascii")
47
            self._colors = {
48
                logging.DEBUG: six.text_type(
49
                    curses.tparm(fg_color, 4),
50
                    "ascii"
51
                ),  # Blue
52
                logging.INFO: six.text_type(
53
                    curses.tparm(fg_color, 2),
54
                    "ascii"
55
                ),  # Green
56
                logging.WARNING: six.text_type(
57
                    curses.tparm(fg_color, 3),
58
                    "ascii"
59
                ),  # Yellow
60
                logging.ERROR: six.text_type(
61
                    curses.tparm(fg_color, 1),
62
                    "ascii"
63
                ),  # Red
64
            }
65
            self._normal = six.text_type(curses.tigetstr("sgr0"), "ascii")
66
67 15
    def format(self, record):
68
        try:
69
            record.message = record.getMessage()
70
        except Exception as e:
71
            record.message = "Bad message (%r): %r" % (e, record.__dict__)
72
        record.asctime = time.strftime(
73
            "%y%m%d %H:%M:%S", self.converter(record.created))
74
        prefix = '[%(levelname)1.1s %(asctime)s %(module)s:%(lineno)d]' % \
75
                 record.__dict__
76
        if self._color:
77
            prefix = (self._colors.get(record.levelno, self._normal) +
78
                      prefix + self._normal)
79
        formatted = prefix + " " + record.message
80
        if record.exc_info:
81
            if not record.exc_text:
82
                record.exc_text = self.formatException(record.exc_info)
83
        if record.exc_text:
84
            formatted = formatted.rstrip() + "\n" + record.exc_text
85
        return formatted.replace("\n", "\n    ")
86