]> code.delx.au - bg-scripts/blob - lib/GregDebug.py
RandomBG: Make Listener non-writeable
[bg-scripts] / lib / GregDebug.py
1 #! python
2
3 import sys
4 import cgitb
5 import inspect
6
7 DEBUG_INCREMENT = 5
8 DEBUG_LEVEL_DEBUG = DEBUG_INCREMENT * -2
9 DEBUG_LEVEL_LOW = DEBUG_INCREMENT * -1
10 DEBUG_LEVEL_MEDIUM = DEBUG_INCREMENT * 0
11 DEBUG_LEVEL_HIGH = DEBUG_INCREMENT * 1
12 DEBUG_LEVEL = DEBUG_LEVEL_MEDIUM
13
14 __stackTraceEnabled = True
15
16 def stackTraceEnabled(value):
17 global __stackTraceEnabled
18 __stackTraceEnabled = value
19
20 def setDebugLevel(level):
21 global DEBUG_LEVEL
22 DEBUG_LEVEL = level
23
24 def isBoundMethod(stackFrame):
25 """Checks to see if the method that is running in the specified stackFrame is
26 a bound method.
27 Returns a 2-tuple containing if it is a bound method, and the object that it is
28 bound to if it is bound."""
29 def errout():
30 return (False, None)
31
32 if stackFrame.f_code.co_argcount < 1:
33 return errout()
34 firstVarName = stackFrame.f_code.co_varnames[0]
35 firstVar = stackFrame.f_locals[firstVarName]
36 if not hasattr(firstVar, stackFrame.f_code.co_name):
37 return errout()
38 if not hasattr(getattr(firstVar, stackFrame.f_code.co_name), 'func_code'):
39 return errout()
40 if getattr(getattr(firstVar, stackFrame.f_code.co_name), 'func_code') == stackFrame.f_code:
41 return (True, firstVar)
42 else:
43 return errout()
44
45 def createStackTrace(stackList):
46 if not __stackTraceEnabled:
47 return ''
48 strStackList = []
49 for stackItem in stackList:
50 stackItemRepr = ""
51 bm = isBoundMethod(stackItem[0]) # stackframe
52 if bm[0]:
53 stackItemRepr = '%s.' % bm[1].__class__.__name__
54 stackItemRepr += stackItem[3] # Function Name
55 del bm # Help remove circular dependencies (reduces memory useage)
56 strStackList.append(stackItemRepr)
57
58 return '=>'.join(strStackList)
59
60 def debug(message, level=DEBUG_LEVEL_MEDIUM, indent_level = None):
61 if level >= DEBUG_LEVEL:
62 stack = inspect.stack()[1:-1] # Ignore this method
63 stack.reverse()
64 if indent_level == None:
65 indent_level = len(stack)
66 for line in message.split('\n'):
67 print >>sys.stderr, '%s %s [%s]' %('>' * indent_level, line, createStackTrace(stack))
68
69 def tracebackHook(etype, evalue, etb):
70 print cgitb.text( (etype, evalue, etb), context = 5)