]> code.delx.au - pymsnt/blob - src/debug.py
0f90522e631b8e37bb2c8be0ef7eb076bdbc4ffd
[pymsnt] / src / debug.py
1 # Copyright 2004-2005 James Bunton <james@delx.cjb.net>
2 # Licensed for distribution under the GPL version 2, check COPYING for details
3
4 from twisted.python import log
5
6 import sys, time
7
8 import config
9
10
11 def observer(eventDict):
12 try:
13 observer2(eventDict)
14 except Exception, e:
15 printf("CRITICAL: Traceback in debug.observer2 - " + str(e))
16
17
18 def observer2(eventDict):
19 edm = eventDict['message']
20 if isinstance(edm, LogEvent):
21 if edm.category == INFO and config._debugLevel < 3:
22 return
23 if (edm.category == WARN or edm.category == ERROR) and config._debugLevel < 2:
24 return
25 text = str(edm)
26 elif edm:
27 if config._debugLevel < 3: return
28 text = ' '.join(map(str, edm))
29 else:
30 if eventDict['isError'] and eventDict.has_key('failure'):
31 if config._debugLevel < 1: return
32 text = eventDict['failure'].getTraceback()
33 elif eventDict.has_key('format'):
34 if config._debugLevel < 3: return
35 text = eventDict['format'] % eventDict
36 else:
37 return
38
39 # Now log it!
40 timeStr = time.strftime("[%Y-%m-%d %H:%M:%S]", time.localtime(eventDict['time']))
41 text = text.replace("\n", "\n\t")
42 global debugFile
43 debugFile.write("%s %s\n" % (timeStr, text))
44 debugFile.flush()
45
46 def printf(text):
47 sys.__stdout__.write(text + "\n")
48 sys.__stdout__.flush()
49
50 debugFile = None
51 def reloadConfig():
52 global debugFile
53 if debugFile:
54 debugFile.close()
55
56 try:
57 config._debugLevel = int(config.debugLevel.strip())
58 except ValueError:
59 config._debugLevel = 0
60 config.debugLevel = "0"
61
62 if config._debugLevel > 0:
63 if len(config.debugFile) > 0:
64 try:
65 debugFile = open(config.debugFile, "a")
66 log.msg("Reopened log file.")
67 except IOError:
68 log.discardLogs() # Give up
69 debugFile = sys.__stdout__
70 return
71 else:
72 debugFile = sys.__stdout__
73
74 log.startLoggingWithObserver(observer)
75 else:
76 log.discardLogs()
77
78 class INFO : pass
79 class WARN : pass
80 class ERROR: pass
81
82 class LogEvent:
83 def __init__(self, category=INFO, ident="", msg="", log=True):
84 self.category, self.ident, self.msg = category, ident, msg
85 frame = sys._getframe(1)
86 # Get the class name
87 s = str(frame.f_locals.get("self", frame.f_code.co_filename))
88 self.klass = s[s.find(".")+1:s.find(" ")]
89 self.method = frame.f_code.co_name
90 self.args = frame.f_locals
91 if log:
92 self.log()
93
94 def __str__(self):
95 args = {}
96 for key in self.args.keys():
97 if key == "self":
98 args["self"] = "instance"
99 continue
100 val = self.args[key]
101 args[key] = val
102 try:
103 if len(val) > 128:
104 args[key] = "Oversize arg"
105 except:
106 # If its not an object with length, assume that it can't be too big. Hope that's a good assumption.
107 pass
108 category = str(self.category).split(".")[1]
109 return "%s :: %s :: %s :: %s :: %s :: %s" % (category, str(self.ident), self.msg, self.method, str(self.klass), str(args))
110
111 def log(self):
112 log.msg(self)
113
114
115