1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 """
28 @summary: Tools not specific for logging purpose
29 @author: Ruben Reifenberg
30 """
31
32
33
35 """
36 Iteriert durch eine gegebene Liste, beginnend mit erstem Element.
37 beginnt im Gegensatz zum Iterator wieder von vorn.
38 @ivar i: index of last returned element
39 """
41 """
42 @param list: len >=1;
43 Behaviour is not defined if list is changed later.
44 """
45 self.list = list
46 self.i = -1
47
49 """
50 Not threadsafe.
51 @return: next list element, rotating
52 @raise IndexError: if list has length 0
53 """
54 self.i += 1
55 if self.i >= len(self.list):
56 self.i = 0
57 return self.list[self.i]
58
61
63 """
64 How many elements to cut away from something with len l,
65 when we want restlen+len(decimal-digit-of-cut-count) < max?
66 @rtype: int
67 @return: count of chars to cut away (cutcount) (can be > l when max is too low)
68 """
69 if l<=max: return 0
70 else:
71 cdl=1
72 cut=10
73 while True:
74 if l-cut+cdl<max:
75 return l-max+cdl
76 cut=cut*10
77 cdl+=1
78
79
80 -def lu2a(unistr, max=50, errorstr="~~~"):
81 """
82 Limited Unicode To Ascii (limited: the result length is limited)
83 Intended for ASCII-logging of untrusted (e.g.user input) unicode strings.
84 The length limitation is intended for storage in length-limited ASCII Database fields.
85 @rtype: ASCII str or None
86 @return: The argument but with: All non-ascii chars replaced by "\\xhexvalue".
87 If N chars (of the result string) are thrown away, "[N+]" is appened at the end.
88 @param unistr: Python Unicode or None
89 @param max: >=3, length limit of the RESULT STRING (default 50)
90 @param errorstr: Returned in case max is too low to return the regular result.
91 """
92 assert max >= 3
93 if unistr is None: return None
94 res = unistr.encode("ascii","backslashreplace")
95 if len(res)>max:
96 cutcount = _cutcount(len(res),max-3)
97 if cutcount<=len(res):
98 res = "%s[%d+]"%(res[:-cutcount],cutcount)
99 else:
100
101 res = errorstr
102 return res
103
104
105 -def lu2a_de(unistr, max=50, errorstr="~~~"):
106 """
107 Note: In case of unistr containing non-ascii characters, this method
108 gets slow (because it does a python loop over each character.)
109 @see: lu2a
110 Additionally, the german umlauts are replaced by AE,OE...
111 to make it more readable (by the drawback of information loss, of course.)
112 """
113 assert max >= 3
114 if unistr is None: return None
115 try:
116
117 res = unistr.encode("ascii")
118 except UnicodeError:
119
120
121
122 res = ""
123 for char in unistr:
124 try:
125 res += char.encode("ascii")
126 except UnicodeError:
127 try:
128 res += {
129 u"\u00e4":"ae",
130 u"\u00f6":"oe",
131 u"\u00fc":"ue",
132 u"\u00c4":"AE",
133 u"\u00d6":"OE",
134 u"\u00dc":"UE",
135 u"\u00df":"ss",
136 }[char]
137 except KeyError:
138 res += char.encode("ascii","backslashreplace")
139 if len(res)>max:
140 cutcount = _cutcount(len(res),max-3)
141 if cutcount<=len(res):
142 res = "%s[%d+]"%(res[:-cutcount],cutcount)
143 else:
144
145 res = errorstr
146 return res
147
148
150 """
151 @param dt: datetime.datetime
152 @param formatStr: strftime format string for dt
153 with an extension: %3N is milliseconds
154 @return: str, made by dt.strftime
155 """
156 formatStr = formatStr.replace("%3N",str(dt.microsecond/1000))
157 return dt.strftime(formatStr)
158
159
160
162 """
163 @param exc_info: as given by sys.exc_info(). If None, it is obtained by calling sys.exc_info
164 @param use_cr: If True, "\\n" is used between the path lines. Otherwise, "<" will separate the lines.
165 @return: short str describing the current ex.stacktrace (end-first),
166 "" if there is no current ex.traceback.
167 """
168 import sys,traceback
169 if exc_info is None:
170 type,value,exc_trace = sys.exc_info()
171 else:
172 type,value,exc_trace = exc_info[0],exc_info[1],exc_info[2]
173 if use_cr: sep = "\n"
174 else: sep = "<"
175 trace=traceback.extract_tb(exc_trace)
176 lines = traceback.format_list(trace)
177 res = ""
178 for i in range(0, len(lines)):
179 if i==maxLines: break
180 if i==0: res = "%s%s%s"%(value,sep,lines[-i-1])
181 else: res += "%s%s"%(sep,lines[-i-1])
182 return res
183
184
186 """
187 Erzeugt einen String, dessen Laenge von der Stacktiefe abhaengt.
188 Verwendungszweck: Einrueckung von Log-Ausgaben.
189 Der String muss nicht unbedingt aus Spaces bestehen; es koennen auch andere "Tokens" angegeben werden.
190 """
191
192 - def __init__(self, token=" ", offset=0):
193 """
194 @param token: str. The resulting string will consist of this tokens.
195 """
196 self.tara(offset)
197 self.token = token
198
199 - def tara(self, depth, tara=0):
200 """
201 "normiert" mich; momentane Stack-Tiefe soll Stringlaenge 0 entsprechen
202 @param tara: wird zu momentaner Stacktiefe zugerechnet
203 """
204 self._offset = depth+tara
205
207 """
208 @return: spaces depending on stack depth
209 """
210 return "".join([self.token for i in range(0, depth-self._offset)])
211
212
213 -def mail_smtp(server,serverpw,to_address,from_address,subject,content,charset="latin-1"):
214 """
215 Sendet subject/content als latin-1.
216 String-Parameter; subject/content may be unicode or str.
217 @return: None
218 @param server: e.g.."mail.gmx.net"
219 @param serverpw: SMTP server password
220 """
221 import smtplib,sys
222 from email.MIMEText import MIMEText
223
224 try:
225 server = smtplib.SMTP(server)
226
227 except:
228 e,f,g = sys.exc_info()
229 print "ERROR:%s,%s"%(e,f)
230 try:
231 server.login(from_address, serverpw)
232 except:
233 e,f,g = sys.exc_info()
234 print "ERROR login:%s,%s"%(e,f)
235
236 msg = MIMEText(content,_charset=charset)
237 msg["From"] = from_address
238 msg["To"] = to_address
239 msg["Subject"] = subject
240 try:
241 server.sendmail(from_address, (to_address,), msg.as_string())
242 except:
243 e,f,g = sys.exc_info()
244 print "ERROR sendmail:%s,%s"%(e,f)
245 try:
246 server.quit()
247 except:
248 e,f,g = sys.exc_info()
249 print "ERROR quit:%s,%s"%(e,f)
250