Package rrlog :: Module tool
[hide private]
[frames] | no frames]

Source Code for Module rrlog.tool

  1  #Copyright (c) 2007 
  2  #        Ruben Reifenberg, Germany, 07381. 
  3  #    All rights reserved. 
  4  # 
  5  #Redistribution and use in source and binary forms, with or without 
  6  #modification, are permitted provided that the following conditions 
  7  #are met: 
  8  #1. Redistributions of source code must retain the above copyright 
  9  #   notice, this list of conditions and the following disclaimer as 
 10  #   the first lines of this file unmodified. 
 11  #2. Redistributions in binary form must reproduce the above copyright 
 12  #   notice, this list of conditions and the following disclaimer in the 
 13  #   documentation and/or other materials provided with the distribution. 
 14  # 
 15  # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 
 16  # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 17  # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 18  # ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 
 19  # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
 20  # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
 21  # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 22  # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
 23  # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
 24  # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
 25  # SUCH DAMAGE. 
 26   
 27  """ 
 28  @summary: Tools not specific for logging purpose 
 29  @author: Ruben Reifenberg 
 30  """ 
 31   
 32   
 33   
34 -class ListRotator(object):
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 """
40 - def __init__(self, list):
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
48 - def next(self):
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
59 - def len(self):
60 return len(self.list)
61
62 -def _cutcount(l, max):
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 #cutcount digit len (e.g. 3 for 100..999) 72 cut=10 #always 10^cdl 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) #3 because "[+]" 97 if cutcount<=len(res): 98 res = "%s[%d+]"%(res[:-cutcount],cutcount) 99 else: 100 #max is too low to display even the count of cut chars 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 # fastest if possible 117 res = unistr.encode("ascii") 118 except UnicodeError: 119 # slow. 120 # Could be faster. But this wants to be is a side effect free library 121 # and we don't want to register a callback handler in codecs globally. 122 res = "" 123 for char in unistr: #don't care for speed. Assume this is seldom. 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") #"<%d>"%(ord(char)) 139 if len(res)>max: 140 cutcount = _cutcount(len(res),max-3) #3 because "[+]" 141 if cutcount<=len(res): 142 res = "%s[%d+]"%(res[:-cutcount],cutcount) 143 else: 144 #max is too low to display even the count of cut chars 145 res = errorstr 146 return res
147 148
149 -def mStrftime(dt, formatStr):
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
161 -def traceToShortStr(maxLines=3,exc_info=None,use_cr=True):
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 = "" # for maxLines==0 or no exception traceback available 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]) #order beginning with end 181 else: res += "%s%s"%(sep,lines[-i-1]) 182 return res
183 184
185 -class StrIndenter(object):
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) #self._offset = 0 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
206 - def __call__(self, depth):
207 """ 208 @return: spaces depending on stack depth 209 """ 210 return "".join([self.token for i in range(0, depth-self._offset)]) #toopt:Py>2.3:use iter
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 #server.set_debuglevel(1) 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