import logging import time; import os,sys,string; import threading; from cloghandler import ConcurrentRotatingFileHandler as RFHandler tPort = None CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 VERBOSE = 5 NOTSET = 0 LOG_LEVEL_LIST = [NOTSET,VERBOSE,DEBUG,INFO,WARNING,ERROR,FATAL] LOG_LEVEL_DICT = { "NOTSET":NOTSET, "VERBOSE":VERBOSE, "DEBUG":DEBUG, "INFO":INFO, "WARNING":WARNING, "ERROR":ERROR, "FATAL":FATAL } LOG_LEVEL = 0 DELIMITER= ' ' PARAMS_DELIMITER = '|' # # _srcfile is used when walking the stack to check when we've got the first # caller stack frame. # WrapperFileName = None if hasattr(sys, 'frozen'): #support for py2exe _srcfile = "logging%s__init__%s" % (os.sep, __file__[-4:]) elif string.lower(__file__[-4:]) in ['.pyc', '.pyo']: _srcfile = __file__[:-4] + '.py' else: _srcfile = __file__ _srcfile = os.path.normcase(_srcfile) class DimdimLogger(): def __init__(self, fileName, bytes = 10000000, count = 10,logLevel=DEBUG,WrapFileName = None): self.logger = logging.getLogger(fileName) console = logging.StreamHandler() console.setLevel(logging.CRITICAL) logging.getLogger('').addHandler(console) self.logger.setLevel(logLevel) self.handler = RFHandler(fileName, "a", bytes, count) self.logger.addHandler(self.handler) global LOG_LEVEL LOG_LEVEL = logLevel global WrapperFileName WrapperFileName = WrapFileName self.info("Logger was initialized to level %s"%(LOG_LEVEL)) def setLogLevel(self,logLevel): global LOG_LEVEL LOG_LEVEL = logLevel if(logLevel==VERBOSE): logLevel = DEBUG self.logger.setLevel(logLevel) self.info("Logger level was set to %s"%(LOG_LEVEL)) def fatal(self,message,e=None,g=None,a=None,r=None,contextParams=None): if LOG_LEVEL<=FATAL: prefixMsg,callerString =self.constructPrefixMsg("FATAL") postMsg = self.constructPostMsg(e, g, a, r, contextParams, message) self.logger.fatal(self.formatString(prefixMsg,postMsg,callerString)) def error(self,message,e=None,g=None,a=None,r=None,contextParams=None): if LOG_LEVEL<=ERROR: prefixMsg,callerString =self.constructPrefixMsg("ERROR") postMsg = self.constructPostMsg(e, g, a, r, contextParams, message) self.logger.exception(self.formatString(prefixMsg,postMsg,callerString)) def exception(self, message,e=None,g=None,a=None,r=None,contextParams=None): self.error(message,e=None,g=None,a=None,r=None,contextParams=None) def warn(self,message,e=None,g=None,a=None,r=None,contextParams=None): if LOG_LEVEL<=WARN: prefixMsg,callerString =self.constructPrefixMsg("WARN") postMsg = self.constructPostMsg(e, g, a, r, contextParams, message) self.logger.warn(self.formatString(prefixMsg,postMsg,callerString)) def info(self,message,e=None,g=None,a=None,r=None,contextParams=None): if LOG_LEVEL<=INFO: prefixMsg,callerString =self.constructPrefixMsg("INFO") postMsg = self.constructPostMsg(e, g, a, r, contextParams, message) self.logger.info(self.formatString(prefixMsg,postMsg,callerString)) def profile(self, message,e=None,g=None,a=None,r=None,contextParams=None): self.info(message,e=None,g=None,a=None,r=None,contextParams=None) def debug(self,message,e=None,g=None,a=None,r=None,contextParams=None): if LOG_LEVEL<=DEBUG: prefixMsg,callerString =self.constructPrefixMsg("DEBUG") postMsg = self.constructPostMsg(e, g, a, r, contextParams, message) self.logger.debug(self.formatString(prefixMsg,postMsg,callerString)) def log(self,message,e=None,g=None,a=None,r=None,contextParams=None): if LOG_LEVEL<=DEBUG: prefixMsg,callerString =self.constructPrefixMsg("DEBUG") postMsg = self.constructPostMsg(e, g, a, r, contextParams, message) self.logger.debug(self.formatString(prefixMsg,postMsg,callerString)) def verbose(self,message,e=None,g=None,a=None,r=None,contextParams=None): if LOG_LEVEL<=VERBOSE: prefixMsg,callerString = self.constructPrefixMsg("VERBOSE") postMsg = self.constructPostMsg(e, g, a, r, contextParams, message) self.logger.debug(self.formatString(prefixMsg,postMsg,callerString)) def fsdebug(self,message): self.logger.debug(message) pass; """ Log format will be in the following [PROCESS ID] [THREAD ID] [OTHER-CONTEXT-PARAMS] """ def formatString(self,prefixMsg, postMsg,callerString): return prefixMsg+DELIMITER+postMsg+DELIMITER+callerString #return prefixMsg+DELIMITER+callerString+DELIMITER+postMsg """ [PROCESS ID] [THREAD ID] """ def constructPrefixMsg(self,logLevel): callerDetails = self.findCaller() fileName = callerDetails[0] className = callerDetails[1] funcName = callerDetails[2] lineNumber = callerDetails[3] global tPort if tPort: pid = str(tPort)+":"+str(os.getpid()) else: pid = str(os.getpid()) if(len(fileName)<28): fileName = self.addSpaces(fileName,28-len(fileName)) if(len(className)<14): className = self.addSpaces(className,14-len(className)) if(len(funcName)<28): funcName = self.addSpaces(funcName,28-len(funcName)) lineNumber = str(lineNumber) if len(lineNumber)<4: lineNumber = self.addSpaces(lineNumber,4-len(lineNumber)) method = str(className)+" "+str(funcName)+" "+str(lineNumber) if(len(logLevel)<8): logLevel = self.addSpaces(logLevel,8-len(logLevel)) theradId = str(threading.currentThread().getName()) if(len(theradId)<11): theradId = self.addSpaces(theradId,11-len(theradId)) return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+DELIMITER+logLevel+DELIMITER+str(pid)+DELIMITER+str(theradId),fileName+' '+method """ [OTHER-CONTEXT-PARAMS] """ def constructPostMsg(self,e,g,a,r,contextParams,message=''): constructedMsg = None confKey = None if e: confKey = str(e) if g: if confKey : confKey = confKey+"____"+str(g) if a: if confKey : confKey = confKey+"____"+str(a) if r: if confKey : confKey = confKey+"____"+str(r) if confKey: constructedMsg = confKey if message: if constructedMsg: constructedMsg = constructedMsg+DELIMITER+str(message) else: constructedMsg = str(message) if contextParams: if constructedMsg: constructedMsg = constructedMsg+DELIMITER+str(contextParams) else: constructedMsg = str(contextParams) return constructedMsg def addSpaces(self,strObj, nSpacesCount): spaces = '' for entry in range(1, nSpacesCount): spaces = spaces+' ' #strObj += spaces return strObj def findCaller(self): f = self.currentframe().f_back filename = "" lineNo = "" methodName = "" className = "" while hasattr(f, "f_code"): co = f.f_code filename = os.path.normcase(co.co_filename) if filename == _srcfile or (WrapperFileName and string.find(filename,WrapperFileName)>-1): f = f.f_back continue if 'self' in f.f_locals and hasattr(f.f_locals['self'],"__class__"): #try: className = f.f_locals['self'].__class__.__name__ #except Exception as ex: # pass lineNo = f.f_lineno methodName = co.co_name break filename = os.path.basename(filename) return filename,className,methodName,lineNo def currentframe(self): """Return the frame object for the caller's stack frame.""" try: raise Exception except: return sys.exc_traceback.tb_frame.f_back