Completed
Push — develop ( dcc6f7...4937ea )
by Wu
9s
created

_LogFormatter.__init__()   B

Complexity

Conditions 3

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 27
rs 8.8571
cc 3
1
# -*- coding:utf-8 -*-
2
3
import six
4
import sys
5
import time
6
import logging
7
8
try:
9
    import curses
10
11
    assert curses
12
except ImportError:
13
    curses = None
14
15
logger = logging.getLogger("WeRoBot")
16
17
18
def enable_pretty_logging(logger, level='info'):
19
    """Turns on formatted logging output as configured.
20
    """
21
    logger.setLevel(getattr(logging, level.upper()))
22
23
    if not logger.handlers:
24
        # Set up color if we are in a tty and curses is installed
25
        color = False
26
        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
        channel = logging.StreamHandler()
34
        channel.setFormatter(_LogFormatter(color=color))
35
        logger.addHandler(channel)
36
37
38
class _LogFormatter(logging.Formatter):
39
    def __init__(self, color, *args, **kwargs):
40
        logging.Formatter.__init__(self, *args, **kwargs)
41
        self._color = color
42
        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
    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