Package install :: Package MoSTBioDat :: Package Log :: Module MoSTBioDatLog
[hide private]
[frames] | no frames]

Source Code for Module install.MoSTBioDat.Log.MoSTBioDatLog

  1  #!/usr/bin/env python 
  2  #################################### 
  3  # MoSTBioDatLog.py:                # 
  4  # Logging for MoSTBioDatDB class   # 
  5  #################################### 
  6   
  7  ###################################################### 
  8  # Copyright (c) 2007-2008 Andrzej Bak                # 
  9  # ARC Seibersdorf & University of Silesia            # 
 10  # Author: Andrzej Bak <Andrzej.Bak@us.edu.pl>        # 
 11  # License: GNU General Public License, version: 3    # 
 12  # URL: http://chemoinformatyka.us.edu.pl/mostbiodat/ # 
 13  # Version: 1, 07.01.2010                             # 
 14  ###################################################### 
 15   
 16  try: 
 17      import os 
 18      import logging 
 19      import sys 
 20      import time 
 21      import pwd 
 22      import types 
 23      import socket 
 24      import fcntl 
 25      import struct 
 26      import netifaces 
 27  except ImportError,e: 
 28      print 'Error: %s' %e 
 29      sys.exit(1) 
 30  ############# Extended Log Record Class ############## 
31 -class ExtendLogRecord(logging.LogRecord):
32 """ 33 Extension of Log Record class 34 INPUT: 35 name - str- name of logger 36 level - set the root logger level to the specified level 37 pathname - str, absolute pathname of source file in which logging call was made 38 lineno - number in that file where logging call is found 39 msg - user-supplied message (a format string) 40 args - tuple which, together with msg, makes up the user message 41 exc_info - exception tuple obtained by calling sys.exc_info() 42 func -name of function logging call was made 43 """
44 - def __init__(self,name, level, pathname, lineno, msg, args, exc_info,func):
45 logging.LogRecord.__init__(self,name, level, pathname, lineno, msg, args, exc_info,func) 46 self.username=getCurrentUser()#add username to logfile 47 self.ip=getLocalIP().getIP()#add ip to logfile 48 self.funcName=func#add function name to logfile
49
50 -class ExtendLogger(logging.getLoggerClass()):
51 """ 52 Extension of Logger Class 53 """
54 - def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func, extra):
55 """ 56 overwriting makeRecord method 57 """ 58 return ExtendLogRecord(name, level, fn, lno, msg, args, exc_info,func)
59
60 - def _log(self, level, msg, args, exc_info=None, extra=None):
61 """ 62 overwriting _log method 63 """ 64 _srcfile=os.path.normcase(getCurrentFile()) 65 if _srcfile: 66 fn, lno, func = self.findCaller() 67 else: 68 fn, lno, func = "(unknown file)", 0, "(unknown function)" 69 if exc_info: 70 if type(exc_info) != types.TupleType: 71 exc_info = sys.exc_info() 72 record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra) 73 self.handle(record)
74 75 logging.setLoggerClass(ExtendLogger) 76 ############### End of class ########################################### 77 ###### Supportive function for Log module ##############################
78 -def getCurrentUser():
79 """ 80 get current user 81 """ 82 try: 83 return pwd.getpwuid(os.getuid()).pw_name 84 except: 85 return "unknown"
86
87 -def callFunctionName():
88 """ 89 get function name 90 """ 91 return callFrame().f_code.co_name
92
93 -def callFrame():
94 """ 95 call Frame 96 """ 97 f=sys._getframe() 98 while True: 99 if isUserSourceFile(f.f_code.co_filename): 100 return f 101 f=f.f_back
102
103 -def isUserSourceFile(filename):
104 """ 105 check if file belongs to specified user 106 """ 107 return os.path.normcase(filename) not in (_srcfile,logging._srcfile)
108
109 -def getCurrentFile():
110 """ 111 get current file 112 """ 113 if __file__[-4:].lower() in ['.pyc','.pyo']: 114 return __file__[:-4]+'.py' 115 else: 116 return __file__
117 118 _srcfile=os.path.normcase(getCurrentFile()) 119
120 -def filterKeys(dictionary,keys,key):
121 """ 122 check input settings 123 """ 124 if key not in keys: 125 del dictionary[key] 126 return False 127 else: 128 return True
129
130 -def datetime():
131 """ 132 generate date/time stamp used in log 133 """ 134 format="%Y-%m-%d %H:%M:%S" 135 datestamp=time.strftime(format,time.localtime(time.time())) 136 return datestamp
137
138 -def geTime(nseconds):
139 """ 140 get time 141 """ 142 seconds=round(nseconds,2) 143 rest=str(seconds).split('.')[1] 144 seconds=int(seconds) 145 min,sec=divmod(seconds,60) 146 hour,min=divmod(min,60) 147 if hour: 148 return '(%d h %02d min %02d.%s sec)' %(hour,min,sec,rest) 149 elif min: 150 return '(%d min %02d.%s sec)' %(min,sec,rest) 151 else: 152 return '(%2d.%s sec)' %(sec,rest)
153 ############ get local host IP address class #######################
154 -class getLocalIP(object):
155 """ 156 get local IP address 157 INPUT: 158 servername - str - servername, default 192.168.1.2 159 port - int - server port, default 22 160 """
161 - def __init__(self,*args,**kwargs):
162 self.kwargs={} 163 self.kwargs=kwargs 164 if len(self.kwargs.keys())==0: 165 self.setup() 166 else: 167 keys=("servername","port") 168 filter(lambda key: filterKeys(kwargs,keys,key),kwargs.keys()) 169 if not self.kwargs.has_key('servername'): 170 self.kwargs.setdefault('servername','192.168.1.2') 171 if not self.kwargs.has_key('port'): 172 self.kwargs.setdefault('port',22)
173
174 - def setup(self):
175 self.kwargs.setdefault('servername','192.168.1.2') 176 self.kwargs.setdefault('port',22)
177
178 - def getIP_1(self,eth0='eth0',eth1='eth1',eth2='eth2'):
179 """ 180 get IP based on ethernet card specification 181 """ 182 try: 183 return self.getEthBaseIP(eth0) 184 except socket.error,e: 185 print "Error %s: %s, %s" %(eth0,e[0],e[1]) 186 try: 187 return self.getEthBaseIP(eth1) 188 except socket.error,e: 189 print "Error %s: %s, %s" %(eth1,e[0],e[1]) 190 try: 191 return self.getEthBaseIP(eth2) 192 except socket.error,e: 193 print "Error %s: %s, %s" %(eth2,e[0],e[1]) 194 try: 195 return self.getNetBaseIP() 196 except socket.error,e: 197 print "Error: %s, %s" %(e[0],e[1]) 198 return "Unknown"
199 200
201 - def getIP(self):
202 """ 203 get IP based on ethernet card specification with netifaces package 204 """ 205 interfaces=netifaces.interfaces() 206 ifaceip=None 207 for iface in interfaces: 208 try: 209 ifaceip=netifaces.ifaddresses(iface)[netifaces.AF_INET] 210 except KeyError,e: 211 # print 'Warning %s: No such device!' %iface 212 continue 213 except ValueError,e: 214 # print 'Error %s: %s' %(iface,e) 215 continue 216 else: 217 if ifaceip[0].has_key('addr'): 218 ifaceip=ifaceip[0]['addr'] 219 if ifaceip!='127.0.0.1': 220 return ifaceip 221 else: 222 ifaceip=None 223 if not (ifaceip and interfaces): 224 ifaceip='127.0.0.1' 225 226 return ifaceip
227 228
229 - def getNetBaseIP(self):
230 """ 231 get IP based on net connection 232 """ 233 try: 234 sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 235 sock.connect((self.kwargs['servername'],self.kwargs['port'])) 236 self.ip, self.localport = sock.getsockname() 237 sock.close() 238 except socket.error,e: 239 print "Connection failed." 240 print "Error: %s, %s" %(e[0],e[1]) 241 else: 242 return self.ip
243
244 - def getEthBaseIP(self,ifname):
245 """ 246 get IP based on socket module 247 """ 248 try: 249 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 250 return socket.inet_ntoa(fcntl.ioctl(sock.fileno(),0x8915, struct.pack('256s',ifname[:15]))[20:24]) 251 except socket.error,e: 252 print "Connection failed." 253 print "Error: %s, %s" %(e[0],e[1])
254 ############### End of class ############################################ 255 ############## MoSTBioDatLog class ######################################
256 -class MoSTBioDatLog(object):
257 """ 258 main MoSTBioDat logging module 259 INPUT: 260 format - str - logging file format, default "%(levelname)s %(asctime)s %(ip)s %(username)s %(filename)s %(module)s %(funcName)s %(lineno)d >> %(message)s " 261 filter - specified record to be logged 262 datefmt - str - date format 263 path - str - path to log files 264 filename - str - log filename, default 'log' 265 filemode - str - log file mode, default 'wa' 266 level - str - logging level, default logging.DEBUG 267 logfilelevel - log file level 268 temporary - str - temporary directory 269 """
270 - def __init__(self,**kwargs):
271 self.kwargs={} 272 self.kwargs=kwargs 273 if len(self.kwargs.keys())==0: 274 self.setup() 275 else: 276 keys=("format","filter","datefmt","path","filename","filemode","level","logfilelevel","temporary") 277 filter(lambda key: filterKeys(kwargs,keys,key),kwargs.keys()) 278 if not self.kwargs.has_key('filename'): 279 self.kwargs.setdefault('filename',None) 280 if (self.kwargs['filename']=='' or self.kwargs['filename'] is None): 281 self.kwargs['filename']='log' 282 if not self.kwargs.has_key('level'): 283 LEVEL=logging.DEBUG 284 self.kwargs.setdefault('level',LEVEL) 285 if not self.kwargs.has_key('format'): 286 FORMAT="%(levelname)s %(asctime)s %(ip)s %(username)s %(filename)s %(module)s %(funcName)s %(lineno)d >> %(message)s " 287 self.kwargs.setdefault('format',FORMAT) 288 if not self.kwargs.has_key('filter'): 289 FILTER=None 290 self.kwargs.setdefault('filter',FILTER) 291 if not self.kwargs.has_key('datefmt'): 292 DATEFORMAT=None 293 self.kwargs.setdefault('datefmt',DATEFORMAT) 294 if not self.kwargs.has_key('filename'): 295 FILENAME='log' 296 self.kwargs.setdefault('filename',FILENAME) 297 if not self.kwargs.has_key('filemode'): 298 FILEMODE='wa' 299 self.kwargs.setdefault('filemode',FILEMODE) 300 if not self.kwargs.has_key('path'): 301 PATH='.' 302 self.kwargs.setdefault('path',PATH) 303 if not self.kwargs.has_key('propagate'): 304 PROPAGATE=True 305 self.kwargs.setdefault('propagate',PROPAGATE) 306 if not self.kwargs.has_key('logfilelevel'): 307 LOGFILELEVEL=logging.DEBUG 308 self.kwargs.setdefault('logfilelevel',LOGFILELEVEL) 309 if not self.kwargs.has_key('temporary'): 310 self.kwargs.setdefault('temporary','/tmp/Log') 311 self.logger=None
312
313 - def setup(self):
314 LEVEL=logging.DEBUG 315 self.kwargs.setdefault('level',LEVEL) 316 FORMAT="%(levelname)s %(asctime)s %(ip)s %(username)s %(filename)s %(module)s %(funcName)s %(lineno)d >> %(message)s " 317 self.kwargs.setdefault('format',FORMAT) 318 FILTER=None 319 self.kwargs.setdefault('filter',FILTER) 320 DATEFORMAT=None 321 self.kwargs.setdefault('datefmt',DATEFORMAT) 322 FILENAME='log' 323 self.kwargs.setdefault('filename',FILENAME) 324 FILEMODE='wa' 325 self.kwargs.setdefault('filemode',FILEMODE) 326 PATH=os.getcwd() 327 self.kwargs.setdefault('path',PATH) 328 PROPAGATE=True 329 self.kwargs.setdefault('propagate',PROPAGATE) 330 LOGFILELEVEL=logging.DEBUG 331 self.kwargs.setdefault('logfilelevel',LOGFILELEVEL) 332 self.kwargs.setdefault('temporary','/tmp/Log')
333
334 - def createlog(self):
335 """ 336 create log file 337 INPUT: 338 class object 339 OUTPUT: 340 """ 341 if self.kwargs['path']=='': 342 self.kwargs['path']=os.path.abspath(os.curdir) 343 if not os.path.isdir(self.kwargs['path']): 344 try: 345 os.makedirs(self.kwargs['path']) 346 except Exception,error: 347 print 'Error: %s, %s for %s' %(error[0],error[1],self.kwargs['path']) 348 self.kwargs['path']=self.kwargs['temporary'] 349 if not os.path.exists(self.kwargs['path']): 350 os.makedirs(self.kwargs['path']) 351 else: 352 if not os.access(self.kwargs['path'],os.W_OK): 353 print 'Error: Permission denied! Unable to write in %s' %self.kwargs['path'] 354 self.kwargs['path']=self.kwargs['temporary'] 355 if not os.path.exists(self.kwargs['path']): 356 os.makedirs(self.kwargs['path']) 357 self.logfullfilename=os.path.join(self.kwargs['path'],self.kwargs['filename']) 358 print 'Log file: %s' %self.logfullfilename
359
360 - def getLogHandler(self):
361 """ 362 get log handler 363 INPUT: 364 class object 365 OUTPUT: 366 """ 367 self.logger=logging.getLogger(self.kwargs['filename']) 368 self.logger.setLevel(self.kwargs['level']) 369 self.createlog() 370 self.logfile = logging.FileHandler(self.logfullfilename +".log") 371 self.logfile.setLevel(self.kwargs['logfilelevel']) 372 formatter=logging.Formatter(self.kwargs['format']) 373 self.logfile.setFormatter(formatter) 374 self.logger.addHandler(self.logfile) 375 return self.logger
376
377 - def rmLogHandler(self):
378 """ 379 remove log handler 380 INPUT: 381 class object 382 OUTPUT: 383 """ 384 self.logger.removeHandler(self.logfile)
385 386
387 - def setLevel(self,levelType):
388 """ 389 set log level 390 INPUT: 391 class object 392 levelType - str - logging levels 393 """ 394 types = {"NOTSET" : logging.NOTSET , 395 "CRITICAL" : logging.CRITICAL, 396 "FATAL" : logging.FATAL, 397 "WARNING" : logging.WARNING, 398 "INFO" : logging.INFO, 399 "DEBUG" : logging.DEBUG } 400 try: 401 self.log.setLevel(types[levelType.upper()]) 402 except KeyError: 403 self.log.warning("Logging error, level selected is not valid : " + levelType)
404 ################### End of class #################### 405 ############## MAIN ################################# 406 ############## Example of usage ##################### 407 if __name__=='__main__': 408 pass 409 # try: 410 # logobj=MoSTBioDatLog(filename='my',path='/tmp/Log')#create logging object 411 # log=logobj.getLogHandler() 412 # log.info('sample sample') 413 # logobj.rmLogHandler() 414 # except IOError,e: 415 # print 'Error : %s, %s' %(e[0],e[1]) 416 # sys.exit(1) 417