summaryrefslogtreecommitdiff
path: root/gbp/log.py
blob: 70f0f108439ab519e41e1d23b4355676de5179bb (plain)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# vim: set fileencoding=utf-8 :
#
# (C) 2010 Guido Guenther <agx@sigxcpu.org>
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
"""Simple colored logging classes"""

import os
import sys
import logging
from logging import (DEBUG, INFO, WARNING, ERROR, CRITICAL, getLogger)


COLORS = dict([('none', 0)] + zip(['black', 'red', 'green', 'yellow', 'blue',
                                   'magenta', 'cyan', 'white'], range(30, 38)))
DEFAULT_COLOR_SCHEME = {DEBUG: COLORS['green'],
                        INFO: COLORS['green'],
                        WARNING: COLORS['red'],
                        ERROR: COLORS['red'],
                        CRITICAL: COLORS['red']}


class GbpFilter(object):
    """Filter for enabling selective output"""
    def __init__(self, levels):
        self._levels = levels

    def filter(self, record):
        """Do we show the record"""
        if record.levelno in self._levels:
            return True
        return False


class GbpStreamHandler(logging.StreamHandler):
    """Special stream handler for enabling colored output"""

    COLOR_SEQ = "\033[%dm"
    OFF_SEQ = "\033[0m"

    def __init__(self, stream=None, color=True):
        super(GbpStreamHandler, self).__init__(stream)
        self._color = color
        msg_fmt = "%(color)s%(name)s:%(levelname)s: %(message)s%(coloroff)s"
        self.setFormatter(logging.Formatter(fmt=msg_fmt))

    def set_color(self, color):
        """Set/unset colorized output"""
        self._color = color

    def set_format(self, fmt):
        """Set logging format"""
        self.setFormatter(logging.Formatter(fmt=fmt))

    def format(self, record):
        """Colorizing formatter"""
        # Never write color-escaped output to non-tty streams
        record.color = record.coloroff = ""
        if self._color and self.stream.isatty():
            record.color = self.COLOR_SEQ % DEFAULT_COLOR_SCHEME[record.levelno]
            record.coloroff = self.OFF_SEQ
        record.levelname = record.levelname.lower()
        return super(GbpStreamHandler, self).format(record)


class GbpLogger(logging.Logger):
    """Logger class for git-buildpackage"""

    def __init__(self, name, color=True, *args, **kwargs):
        super(GbpLogger, self).__init__(name, *args, **kwargs)
        self._default_handlers = [GbpStreamHandler(sys.stdout, color),
                                  GbpStreamHandler(sys.stderr, color)]
        self._default_handlers[0].addFilter(GbpFilter([DEBUG, INFO]))
        self._default_handlers[1].addFilter(GbpFilter([WARNING, ERROR,
                                                       CRITICAL]))
        for hdlr in self._default_handlers:
            self.addHandler(hdlr)

    def set_color(self, color):
        """Set/unset colorized output of the default handlers"""
        for hdlr in self._default_handlers:
            hdlr.set_color(color)

    def set_format(self, fmt):
        """Set the format of the default handlers"""
        for hdlr in self._default_handlers:
            hdlr.set_format(fmt)


def err(msg):
    """Logs a message with level ERROR on the GBP logger"""
    LOGGER.error(msg)

def warn(msg):
    """Logs a message with level WARNING on the GBP logger"""
    LOGGER.warning(msg)

def info(msg):
    """Logs a message with level INFO on the GBP logger"""
    LOGGER.info(msg)

def debug(msg):
    """Logs a message with level DEBUG on the GBP logger"""
    LOGGER.debug(msg)

def _use_color(color):
    """Parse the color option"""
    if isinstance(color, bool):
        return color
    else:
        if color.is_on():
            return True
        elif color.is_auto():
            in_emacs = (os.getenv("EMACS") and
                        os.getenv("INSIDE_EMACS", "").endswith(",comint"))
            return not in_emacs
    return False

def setup(color, verbose):
    """Basic logger setup"""
    LOGGER.set_color(_use_color(color))
    if verbose:
        LOGGER.setLevel(DEBUG)
    else:
        LOGGER.setLevel(INFO)


# Initialize the module
logging.setLoggerClass(GbpLogger)

LOGGER = getLogger("gbp")