summaryrefslogtreecommitdiff
path: root/kiwi/log.py
blob: 9cd5f6374922074bde126997afa0911264f07ff2 (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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
#
# Kiwi: a Framework and Enhanced Widgets for Python
#
# Copyright (C) 2005-2006 Async Open Source
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
# USA
#
# Author(s): Johan Dahlin     <jdahlin@async.com.br>
#

"""
Extension to the logging module

This module defines a couple of extensions to the logging module included
in the python standard distribution.

It creates an additional logging handler that print log records on the
standard output. This handler is only showing records which has a level
set to logging.WARNING or higher by default.
The messages printed by this handler can be modified by using the environment
variable called KIWI_LOG.

The syntax for the string which KIWI_LOG points to is the following::

    domain ':' level [, domain ':', level]

domain can contain wildcards such as * and ?
level is an integer 1-5 which defines the minimal level:

  - B{5}: DEBUG
  - B{4}: INFO
  - B{3}: WARNING
  - B{2}: ERROR
  - B{1}: CRITICAL

Examples::

    KIWI_LOG="stoq*:5"

will print all the messages in a domain starting with stoq with DEBUG or higher::

    KIWI_LOG="kiwi*:4,stoq.*:5"

will print all the messages with INFO or higher in all domains starting with kiwi,
and all the messages in the stoq.* domains which are DEBUG or higher

Inspiration for the syntax is taken from the U{debugging facilities<http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer/html/gstreamer-GstInfo.html#id2857358>} of the
U{GStreamer<http://www.gstreamer.net>} multimedia framework.
"""

import fnmatch
import logging
import os

# Globals

_console = None
_filter = None

class LogError(Exception):
    pass

class Logger(object):
    # Backwards compatibility, we should probably replace the callsites
    # with import logging; logging.getLogger(name)
    def __new__(self, name):
        return logging.getLogger(name)

class _Logger(logging.Logger):
    def __call__(self, message, *args, **kwargs):
        self.info(message, *args, **kwargs)

logging.setLoggerClass(_Logger)

class ReversedGlobalFilter(logging.Filter):
    """
    It's like a reversed filter, the default behavior
    is to not show the message, you need to add custom filters for all
    the records you wish to see
    """
    def __init__(self):
        logging.Filter.__init__(self)
        self.filters = []

    def add_filter(self, f, level=logging.DEBUG):
        self.filters.append((f, level))

    def filter(self, record):
        for f, level in self.filters:
            if (record.levelno >= level and
                fnmatch.fnmatch(record.name, f)):
                return True

        return False

def set_log_file(filename, mask=None):
    """
    @param filename:
    @param mask: optional
    """
    file_handler = logging.FileHandler(filename, 'w')
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(name)-18s %(levelname)-8s %(message)s',
        datefmt='%F %T'))
    root = logging.getLogger()
    root.addHandler(file_handler)

    if mask:
        file_filter = ReversedGlobalFilter()
        file_filter.add_filter(mask, logging.DEBUG)
        file_handler.addFilter(file_filter)

    return file_handler.stream

def set_log_level(name, level):
    """
    @param name: logging category
    @param level: level
    """
    global _filter
    _filter.add_filter(name, level)

def _read_log_levels(console_filter):
    log_levels = {}
    # bootstrap issue, cannot depend on kiwi.environ
    log_level = os.environ.get('KIWI_LOG')
    if not log_level:
        return log_levels

    for part in log_level.split(','):
        if not ':' in part:
            continue

        if part.count(':') > 1:
            raise LogError("too many : in part %s" % part)
        name, level = part.split(':')
        try:
            level = int(level)
        except ValueError:
            raise LogError("invalid level: %s" % level)

        if level < 0 or level > 5:
            raise LogError("level must be between 0 and 5")

        level = 50 - (level * 10)

        console_filter.add_filter(name, level)

def _create_console():
    global _filter, _console

    console = logging.StreamHandler()
    console.setFormatter(logging.Formatter(
        "%(asctime)s %(name)-20s %(message)s", datefmt='%T'))
    root = logging.getLogger()
    root.addHandler(console)
    root.setLevel(logging.DEBUG)

    console_filter = ReversedGlobalFilter()
    # Always display warnings or higher on the console
    console_filter.add_filter('*', logging.WARNING)
    console.addFilter(console_filter)

    _read_log_levels(console_filter)

    # Set globals
    _filter = console_filter
    _console = console

_create_console()

kiwi_log = Logger('kiwi')