don't open twice the same subscription request dialog. see #6762
[gajim.git] / src / common / logging_helpers.py
blobd8f73bf6564c03952f8918f25191a927d0cb55fb
1 # -*- coding:utf-8 -*-
2 ## src/common/logging_helpers.py
3 ##
4 ## Copyright (C) 2009 Bruno Tarquini <btarquini AT gmail.com>
5 ##
6 ## This file is part of Gajim.
7 ##
8 ## Gajim is free software; you can redistribute it and/or modify
9 ## it under the terms of the GNU General Public License as published
10 ## by the Free Software Foundation; version 3 only.
12 ## Gajim is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ## GNU General Public License for more details.
17 ## You should have received a copy of the GNU General Public License
18 ## along with Gajim. If not, see <http://www.gnu.org/licenses/>.
21 import logging
22 import i18n
24 def parseLogLevel(arg):
25 """
26 Eiter numeric value or level name from logging module
27 """
28 if arg.isdigit():
29 return int(arg)
30 elif arg.isupper() and hasattr(logging, arg):
31 return getattr(logging, arg)
32 else:
33 print _('%s is not a valid loglevel') % repr(arg)
34 return 0
36 def parseLogTarget(arg):
37 """
38 [gajim.]c.x.y -> gajim.c.x.y
39 .other_logger -> other_logger
40 <None> -> gajim
41 """
42 arg = arg.lower()
43 if not arg:
44 return 'gajim'
45 elif arg.startswith('.'):
46 return arg[1:]
47 elif arg.startswith('gajim'):
48 return arg
49 else:
50 return 'gajim.' + arg
52 def parseAndSetLogLevels(arg):
53 """
54 [=]LOGLEVEL -> gajim=LOGLEVEL
55 gajim=LOGLEVEL -> gajim=LOGLEVEL
56 .other=10 -> other=10
57 .=10 -> <nothing>
58 c.x.y=c.z=20 -> gajim.c.x.y=20
59 gajim.c.z=20
60 gajim=10,c.x=20 -> gajim=10
61 gajim.c.x=20
62 """
63 for directive in arg.split(','):
64 directive = directive.strip()
65 if not directive:
66 continue
67 if '=' not in directive:
68 directive = '=' + directive
69 targets, level = directive.rsplit('=', 1)
70 level = parseLogLevel(level.strip())
71 for target in targets.split('='):
72 target = parseLogTarget(target.strip())
73 if target:
74 logging.getLogger(target).setLevel(level)
75 print "Logger %s level set to %d" % (target, level)
78 class colors:
79 NONE = chr(27) + "[0m"
80 BLACk = chr(27) + "[30m"
81 RED = chr(27) + "[31m"
82 GREEN = chr(27) + "[32m"
83 BROWN = chr(27) + "[33m"
84 BLUE = chr(27) + "[34m"
85 MAGENTA = chr(27) + "[35m"
86 CYAN = chr(27) + "[36m"
87 LIGHT_GRAY = chr(27) + "[37m"
88 DARK_GRAY = chr(27) + "[30;1m"
89 BRIGHT_RED = chr(27) + "[31;1m"
90 BRIGHT_GREEN = chr(27) + "[32;1m"
91 YELLOW = chr(27) + "[33;1m"
92 BRIGHT_BLUE = chr(27) + "[34;1m"
93 PURPLE = chr(27) + "[35;1m"
94 BRIGHT_CYAN = chr(27) + "[36;1m"
95 WHITE = chr(27) + "[37;1m"
97 def colorize(text, color):
98 return color + text + colors.NONE
100 class FancyFormatter(logging.Formatter):
102 An eye-candy formatter with colors
104 colors_mapping = {
105 'DEBUG': colors.BLUE,
106 'INFO': colors.GREEN,
107 'WARNING': colors.BROWN,
108 'ERROR': colors.RED,
109 'CRITICAL': colors.BRIGHT_RED,
112 def __init__(self, fmt, datefmt=None, use_color=False):
113 logging.Formatter.__init__(self, fmt, datefmt)
114 self.use_color = use_color
116 def formatTime(self, record, datefmt=None):
117 f = logging.Formatter.formatTime(self, record, datefmt)
118 if self.use_color:
119 f = colorize(f, colors.DARK_GRAY)
120 return f
122 def format(self, record):
123 level = record.levelname
124 record.levelname = '(%s)' % level[0]
126 if self.use_color:
127 c = FancyFormatter.colors_mapping.get(level, '')
128 record.levelname = colorize(record.levelname, c)
129 record.name = colorize(record.name, colors.CYAN)
130 else:
131 record.name += ':'
133 return logging.Formatter.format(self, record)
136 def init(use_color=False):
138 Iinitialize the logging system
140 consoleloghandler = logging.StreamHandler()
141 consoleloghandler.setFormatter(
142 FancyFormatter(
143 '%(asctime)s %(levelname)s %(name)s %(message)s',
144 '%H:%M:%S',
145 use_color
149 # fake the root logger so we have 'gajim' root name instead of 'root'
150 root_log = logging.getLogger('gajim')
151 root_log.setLevel(logging.WARNING)
152 root_log.addHandler(consoleloghandler)
153 root_log.propagate = False
155 def set_loglevels(loglevels_string):
156 parseAndSetLogLevels(loglevels_string)
158 def set_verbose():
159 parseAndSetLogLevels('gajim=1')
161 def set_quiet():
162 parseAndSetLogLevels('gajim=CRITICAL')
165 # tests
166 if __name__ == '__main__':
167 init(use_color=True)
169 set_loglevels('gajim.c=DEBUG,INFO')
171 log = logging.getLogger('gajim')
172 log.debug('debug')
173 log.info('info')
174 log.warn('warn')
175 log.error('error')
176 log.critical('critical')
178 log = logging.getLogger('gajim.c.x.dispatcher')
179 log.debug('debug')
180 log.info('info')
181 log.warn('warn')
182 log.error('error')
183 log.critical('critical')