27f98858244022e5de980280a5ec4bb1ec8f982f
[plcapi.git] / PLC / Debug.py
1 # log system for PLCAPI
2 import time
3 import sys
4 import syslog
5
6 class unbuffered:
7     """
8     Write to /var/log/httpd/error_log. See
9
10     http://www.modpython.org/FAQ/faqw.py?req=edit&file=faq02.003.htp
11     """
12
13     def write(self, data):
14         sys.stderr.write(data)
15         sys.stderr.flush()
16
17 log = unbuffered()
18
19 def profile(callable):
20     """
21     Prints the runtime of the specified callable. Use as a decorator, e.g.,
22
23         @profile
24         def foo(...):
25             ...
26
27     Or, equivalently,
28
29         def foo(...):
30             ...
31         foo = profile(foo)
32
33     Or inline:
34
35         result = profile(foo)(...)
36     """
37
38     def wrapper(*args, **kwds):
39         start = time.time()
40         result = callable(*args, **kwds)
41         end = time.time()
42         args = map(str, args)
43         args += ["%s = %s" % (name, str(value)) for (name, value) in kwds.items()]
44         print >> log, "%s (%s): %f s" % (callable.__name__, ", ".join(args), end - start)
45         return result
46
47     return wrapper
48
49 if __name__ == "__main__":
50     def sleep(seconds = 1):
51         time.sleep(seconds)
52
53     sleep = profile(sleep)
54
55     sleep(1)