3 ## Copyright (C) 2003 Jacob Lundqvist
5 ## This program is free software; you can redistribute it and/or modify
6 ## it under the terms of the GNU Lesser General Public License as published
7 ## by the Free Software Foundation; either version 2, or (at your option)
10 ## This program is distributed in the hope that it will be useful,
11 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 ## GNU Lesser General Public License for more details.
21 Other modules can always define extra debug flags for local usage, as long as
22 they make sure they append them to debug_flags
24 Also its always a good thing to prefix local flags with something, to reduce risk
25 of coliding flags. Nothing breaks if two flags would be identical, but it might
26 activate unintended debugging.
28 flags can be numeric, but that makes analysing harder, on creation its
29 not obvious what is activated, and when flag_show is given, output isnt
32 This Debug class can either be initialized and used on app level, or used independantly
33 by the individual classes.
35 For samples of usage, see samples subdir in distro source, and selftest
49 if os
.environ
.has_key('TERM'):
54 color_none
= chr(27) + "[0m"
55 color_black
= chr(27) + "[30m"
56 color_red
= chr(27) + "[31m"
57 color_green
= chr(27) + "[32m"
58 color_brown
= chr(27) + "[33m"
59 color_blue
= chr(27) + "[34m"
60 color_magenta
= chr(27) + "[35m"
61 color_cyan
= chr(27) + "[36m"
62 color_light_gray
= chr(27) + "[37m"
63 color_dark_gray
= chr(27) + "[30;1m"
64 color_bright_red
= chr(27) + "[31;1m"
65 color_bright_green
= chr(27) + "[32;1m"
66 color_yellow
= chr(27) + "[33;1m"
67 color_bright_blue
= chr(27) + "[34;1m"
68 color_purple
= chr(27) + "[35;1m"
69 color_bright_cyan
= chr(27) + "[36;1m"
70 color_white
= chr(27) + "[37;1m"
74 Define your flags in yor modules like this:
78 DBG_INIT = 'init' ; debug_flags.append( DBG_INIT )
79 DBG_CONNECTION = 'connection' ; debug_flags.append( DBG_CONNECTION )
81 The reason for having a double statement wis so we can validate params
82 and catch all undefined debug flags
84 This gives us control over all used flags, and makes it easier to allow
85 global debugging in your code, just do something like
87 foo = Debug( debug_flags )
89 group flags, that is a flag in it self containing multiple flags should be
90 defined without the debug_flags.append() sequence, since the parts are already
91 in the list, also they must of course be defined after the flags they depend on ;)
94 DBG_MULTI = [ DBG_INIT, DBG_CONNECTION ]
100 To speed code up, typically for product releases or such
101 use this class instead if you globaly want to disable debugging
106 def __init__( self
, *args
, **kwargs
):
107 self
.debug_flags
= []
108 def show( self
, *args
, **kwargs
):
110 def Show( self
, *args
, **kwargs
):
112 def is_active( self
, flag
):
115 def active_set( self
, active_flags
= None ):
125 # active_flags are those that will trigger output
129 # Log file should be file object or file namne
131 log_file
= sys
.stderr
,
133 # prefix and sufix can either be set globaly or per call.
134 # personally I use this to color code debug statements
135 # with prefix = chr(27) + '[34m'
136 # sufix = chr(27) + '[37;1m\n'
141 # If you want unix style timestamps,
142 # 0 disables timestamps
143 # 1 before prefix, good when prefix is a string
144 # 2 after prefix, good when prefix is a color
148 # flag_show should normaly be of, but can be turned on to get a
149 # good view of what flags are actually used for calls,
150 # if it is not None, it should be a string
151 # flags for current call will be displayed
152 # with flag_show as separator
153 # recomended values vould be '-' or ':', but any string goes
157 # If you dont want to validate flags on each call to
158 # show(), set this to 0
162 # If you dont want the welcome message, set to 0
163 # default is to show welcome if any flags are active
167 self
.debug_flags
= []
169 if active_flags
and len(active_flags
):
174 self
._remove
_dupe
_flags
()
176 if type( log_file
) is type(''):
178 self
._fh
= open(log_file
,'w')
180 print 'ERROR: can open %s for writing'
182 else: ## assume its a stream type object
185 self
._fh
= sys
.stdout
187 if time_stamp
not in (0,1,2):
188 msg2
= '%s' % time_stamp
189 raise 'Invalid time_stamp param', msg2
192 self
.time_stamp
= time_stamp
193 self
.flag_show
= None # must be initialised after possible welcome
194 self
.validate_flags
= validate_flags
196 self
.active_set( active_flags
)
199 caller
= sys
._getframe
(1) # used to get name of caller
201 mod_name
= ":%s" % caller
.f_locals
['__name__']
204 self
.show('Debug created for %s%s' % (caller
.f_code
.co_filename
,
206 self
.show(' flags defined: %s' % ','.join( self
.active
))
208 if type(flag_show
) in (type(''), type(None)):
209 self
.flag_show
= flag_show
211 msg2
= '%s' % type(flag_show
)
212 raise 'Invalid type for flag_show!', msg2
218 def show( self
, msg
, flag
= None, prefix
= None, sufix
= None,
221 flag can be of folowing types:
222 None - this msg will always be shown if any debugging is on
223 flag - will be shown if flag is active
224 (flag1,flag2,,,) - will be shown if any of the given flags
227 if prefix / sufix are not given, default ones from init will be used
229 lf = -1 means strip linefeed if pressent
230 lf = 1 means add linefeed if not pressent
233 if self
.validate_flags
:
234 self
._validate
_flag
( flag
)
236 if not self
.is_active(flag
):
247 if self
.time_stamp
== 2:
248 output
= '%s%s ' % ( pre
,
249 time
.strftime('%b %d %H:%M:%S',
250 time
.localtime(time
.time() )),
252 elif self
.time_stamp
== 1:
253 output
= '%s %s' % ( time
.strftime('%b %d %H:%M:%S',
254 time
.localtime(time
.time() )),
262 output
= '%s%s%s' % ( output
, flag
, self
.flag_show
)
264 # this call uses the global default,
265 # dont print "None", just show the separator
266 output
= '%s %s' % ( output
, self
.flag_show
)
268 output
= '%s%s%s' % ( output
, msg
, suf
)
270 # strip/add lf if needed
271 last_char
= output
[-1]
272 if lf
== 1 and last_char
!= LINE_FEED
:
273 output
= output
+ LINE_FEED
274 elif lf
== -1 and last_char
== LINE_FEED
:
277 self
._fh
.write( output
)
279 # unicode strikes again ;)
281 for i
in range(len(output
)):
282 if ord(output
[i
]) < 128:
287 self
._fh
.write( '%s%s%s' % ( pre
, s
, suf
))
291 def is_active( self
, flag
):
292 'If given flag(s) should generate output.'
294 # try to abort early to quicken code
297 if not flag
or flag
in self
.active
:
300 # check for multi flag type:
301 if type( flag
) in ( type(()), type([]) ):
308 def active_set( self
, active_flags
= None ):
309 "returns 1 if any flags where actually set, otherwise 0."
315 elif type( active_flags
) in ( types
.TupleType
, types
.ListType
):
316 flags
= self
._as
_one
_list
( active_flags
)
318 if t
not in self
.debug_flags
:
319 sys
.stderr
.write('Invalid debugflag given: %s\n' % t
)
322 self
.active
= ok_flags
325 # assume comma string
327 flags
= active_flags
.split(',')
330 self
.show( '*** Invalid debug param given: %s' % active_flags
)
331 self
.show( '*** please correct your param!' )
332 self
.show( '*** due to this, full debuging is enabled' )
333 self
.active
= self
.debug_flags
338 self
.active
= ok_flags
340 self
._remove
_dupe
_flags
()
343 def active_get( self
):
344 "returns currently active flags."
348 def _as_one_list( self
, items
):
349 """ init param might contain nested lists, typically from group flags.
351 This code organises lst and remves dupes
353 if type( items
) <> type( [] ) and type( items
) <> type( () ):
357 if type( l
) == type([]):
358 lst2
= self
._as
_one
_list
( l
)
360 self
._append
_unique
_str
(r
, l2
)
364 self
._append
_unique
_str
(r
, l
)
368 def _append_unique_str( self
, lst
, item
):
369 """filter out any dupes."""
370 if type(item
) <> type(''):
372 raise 'Invalid item type (should be string)',msg2
378 def _validate_flag( self
, flags
):
379 'verify that flag is defined.'
381 for f
in self
._as
_one
_list
( flags
):
382 if not f
in self
.debug_flags
:
384 raise 'Invalid debugflag given', msg2
386 def _remove_dupe_flags( self
):
388 if multiple instances of Debug is used in same app,
389 some flags might be created multiple time, filter out dupes
392 for f
in self
.debug_flags
:
393 if f
not in unique_flags
:
394 unique_flags
.append(f
)
395 self
.debug_flags
= unique_flags
398 def Show(self
, flag
, msg
, prefix
=''):
399 msg
=msg
.replace('\r','\\r').replace('\n','\\n').replace('><','>\n <')
400 if not colors_enabled
: pass
401 elif self
.colors
.has_key(prefix
): msg
=self
.colors
[prefix
]+msg
+color_none
402 else: msg
=color_none
+msg
403 if not colors_enabled
: prefixcolor
=''
404 elif self
.colors
.has_key(flag
): prefixcolor
=self
.colors
[flag
]
405 else: prefixcolor
=color_none
408 _exception
= sys
.exc_info()
410 msg
=msg
+'\n'+''.join(traceback
.format_exception(_exception
[0], _exception
[1], _exception
[2])).rstrip()
412 prefix
= self
.prefix
+prefixcolor
+(flag
+' '*12)[:12]+' '+(prefix
+' '*6)[:6]
413 self
.show(msg
, flag
, prefix
)
415 def is_active( self
, flag
):
416 if not self
.active
: return 0
417 if not flag
or flag
in self
.active
and DBG_ALWAYS
not in self
.active
or flag
not in self
.active
and DBG_ALWAYS
in self
.active
: return 1
422 ##Uncomment this to effectively disable all debugging and all debugging overhead.