trying out the hint from github issue
[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         params = map(str, args)
43         params += ["{} = {}".format(name, value) for (name, value) in kwds.items()]
44         params = ", ".join(params)
45         print >> log, "{} ({}) {:f}s -> {}".format(callable.__name__, params, end - start, result)
46         return result
47
48     return wrapper
49
50 if __name__ == "__main__":
51     def sleep(seconds = 1):
52         time.sleep(seconds)
53
54     sleep = profile(sleep)
55
56     sleep(1)