File: log.py

package info (click to toggle)
python-pecan 1.3.3-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,324 kB
  • sloc: python: 10,399; makefile: 130; sh: 12
file content (54 lines) | stat: -rw-r--r-- 1,670 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import logging

from logutils.colorize import ColorizingStreamHandler


class DefaultColorizer(ColorizingStreamHandler):

    level_map = {
        logging.DEBUG: (None, 'blue', True),
        logging.INFO: (None, None, True),
        logging.WARNING: (None, 'yellow', True),
        logging.ERROR: (None, 'red', True),
        logging.CRITICAL: (None, 'red', True),
    }


class ColorFormatter(logging.Formatter):
    """
    A very basic logging formatter that not only applies color to the
    levels of the ouput but can also add padding to the the level names so that
    they do not alter the visuals of logging when presented on the terminal.

    The padding is provided by a convenient keyword that adds padding to the
    ``levelname`` so that log output is easier to follow::

        %(padded_color_levelname)s

    Which would result in log level output that looks like::

        [INFO    ]
        [WARNING ]
        [ERROR   ]
        [DEBUG   ]
        [CRITICAL]

    If colored output is not supported, it falls back to non-colored output
    without any extra settings.
    """

    def __init__(self, _logging=None, colorizer=None, *a, **kw):
        self.logging = _logging or logging
        self.color = colorizer or DefaultColorizer()
        logging.Formatter.__init__(self, *a, **kw)

    def format(self, record):
        levelname = record.levelname
        padded_level = '%-8s' % levelname

        record.color_levelname = self.color.colorize(levelname, record)
        record.padded_color_levelname = self.color.colorize(
            padded_level,
            record
        )
        return self.logging.Formatter.format(self, record)