NetworkConstants.py + ConfigOptions.py = Constants.py
[straw.git] / straw / error.py
blob7b5a16f911ccd350eb4ca50faafda8e659a87aee
1 """ error.py
3 Module for logging errors
4 """
5 __copyright__ = "Copyright (c) 2002-2005 Free Software Foundation, Inc."
6 __license__ = """ GNU General Public License
8 This program is free software; you can redistribute it and/or modify it under the
9 terms of the GNU General Public License as published by the Free Software
10 Foundation; either version 2 of the License, or (at your option) any later
11 version.
13 This program is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License along with
18 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
19 Place - Suite 330, Boston, MA 02111-1307, USA. """
21 import sys
22 import traceback
23 import pprint
24 from StringIO import StringIO
25 import logging
27 stream = sys.stderr
29 def setup_log():
30 logging.basicConfig(level=logging.DEBUG,
31 format='%(asctime)s %(levelname)-8s %(message)s',
32 datefmt='%m-%d %H:%M',
33 filename='straw.log',
34 filemode='a')
36 console = logging.StreamHandler()
37 console.setLevel(logging.DEBUG)
38 formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
39 console.setFormatter(formatter)
40 logging.getLogger('').addHandler(console)
42 def debug(msg, *args, **kwargs):
43 logging.debug(msg)
45 def log(*args):
46 caller = traceback.extract_stack()[-2]
47 _log(caller, *args)
49 def _log(caller = None, *args):
50 if caller is None:
51 caller = traceback.extract_stack()[-2]
52 try:
53 cf = caller[0][caller[0].rindex("/")+1:]
54 except:
55 cf = caller[0]
56 stream.write("%s:%d:%s: " % (cf, caller[1], caller[2]))
57 for a in args:
58 if type(a) is not type(''):
59 a = repr(a)
60 stream.write(a)
61 stream.write("\n")
63 def logtb(*args):
64 _log(traceback.extract_stack()[-2], *args)
65 l = traceback.format_list(traceback.extract_stack()[:-1])
66 for e in l:
67 stream.write(e)
69 def logparam(locals, *vars):
70 logargs = []
71 for v in vars:
72 logargs.append(v + ": " + str(locals[v]))
73 _log(traceback.extract_stack()[-2], ", ".join(logargs))
75 def logpparam(locals, *vars):
76 logargs = []
77 for v in vars:
78 sio = StringIO()
79 pprint.pprint(locals[v], sio)
80 logargs.append(v + ": " + sio.getvalue())
81 sio.close()
82 _log(traceback.extract_stack()[-2], "".join(logargs))
85 depth = 0
86 def incr_depth():
87 global depth
88 depth += 1
89 def decr_depth():
90 global depth
91 depth -= 1
92 def get_indent(): return " " * depth
94 def debug_around(f):
95 caller = traceback.extract_stack()[-2]
97 def f2(*args, **kwargs):
98 def maybe_str(o):
99 if isinstance(o, str):
100 return repr(o)
101 return str(o)
102 indent = get_indent()
103 _log(caller, "%sEntering " % indent, f.__name__)
104 argstr = ", ".join([maybe_str(a) for a in args])
105 if len(kwargs) > 0:
106 argstr += ", " + ", ".join(
107 ["%s: %s" % (maybe_str(k), maybe_str(v))
108 for k, v in kwargs.items()])
109 _log(caller, "%sArgs: (" % indent, argstr, ")")
110 incr_depth()
111 r = None
112 try:
113 r = f(*args, **kwargs)
114 finally:
115 decr_depth()
116 _log(caller, "%sReturning %s from %s" % (
117 indent, str(r), f.__name__))
118 return r
121 return f2
123 # Originally by Bryn Keller
124 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52215
125 def log_exc(message):
127 Print the usual traceback information, followed by a listing of all the
128 local variables in each frame.
130 _log(traceback.extract_stack()[-2], message)
131 tb = sys.exc_info()[2]
132 while 1:
133 if not tb.tb_next:
134 break
135 tb = tb.tb_next
136 stack = []
137 f = tb.tb_frame
138 while f:
139 stack.append(f)
140 f = f.f_back
141 stack.reverse()
142 traceback.print_exc()
143 print >>stream, "Locals by frame, innermost last"
144 for frame in stack:
145 print >>stream
146 print >>stream, "Frame %s in %s at line %s" % (
147 frame.f_code.co_name, frame.f_code.co_filename,
148 frame.f_lineno)
149 for key, value in frame.f_locals.items():
150 print >>stream, "\t%20s = " % key,
151 #We have to be careful not to cause a new error in our error
152 #printer! Calling str() on an unknown object could cause an
153 #error we don't want.
154 try:
155 print >>stream, value
156 except:
157 print >>stream, "<ERROR WHILE PRINTING VALUE>"