5 import logging, logging.handlers
7 CRITICAL=logging.CRITICAL
9 WARNING=logging.WARNING
13 # a logger that can handle tracebacks
15 def __init__ (self,logfile=None,loggername=None,level=logging.INFO):
16 # default is to locate loggername from the logfile if avail.
19 #handler=logging.StreamHandler()
20 #handler.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
21 logfile = "/var/log/sfa.log"
24 loggername=os.path.basename(logfile)
26 handler=logging.handlers.RotatingFileHandler(logfile,maxBytes=1000000, backupCount=5)
28 # This is usually a permissions error becaue the file is
29 # owned by root, but httpd is trying to access it.
30 tmplogfile=os.getenv("TMPDIR", "/tmp") + os.path.sep + os.path.basename(logfile)
31 # In strange uses, 2 users on same machine might use same code,
32 # meaning they would clobber each others files
33 # We could (a) rename the tmplogfile, or (b)
34 # just log to the console in that case.
35 # Here we default to the console.
36 if os.path.exists(tmplogfile) and not os.access(tmplogfile,os.W_OK):
37 loggername = loggername + "-console"
38 handler = logging.StreamHandler()
40 handler=logging.handlers.RotatingFileHandler(tmplogfile,maxBytes=1000000, backupCount=5)
41 handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
42 self.logger=logging.getLogger(loggername)
43 self.logger.setLevel(level)
44 # check if logger already has the handler we're about to add
45 handler_exists = False
46 for l_handler in self.logger.handlers:
47 if l_handler.baseFilename == handler.baseFilename and \
48 l_handler.level == handler.level:
51 if not handler_exists:
52 self.logger.addHandler(handler)
54 self.loggername=loggername
56 def setLevel(self,level):
57 self.logger.setLevel(level)
59 # shorthand to avoid having to import logging all over the place
60 def setLevelDebug(self):
61 self.logger.setLevel(logging.DEBUG)
63 # define a verbose option with s/t like
64 # parser.add_option("-v", "--verbose", action="count", dest="verbose", default=0)
65 # and pass the coresponding options.verbose to this method to adjust level
66 def setLevelFromOptVerbose(self,verbose):
68 self.logger.setLevel(logging.WARNING)
70 self.logger.setLevel(logging.INFO)
72 self.logger.setLevel(logging.DEBUG)
79 self.logger.debug(msg)
84 # some code is using logger.warn(), some is using logger.warning()
85 def warning(self, msg):
86 self.logger.warning(msg)
89 self.logger.error(msg)
91 def critical(self, msg):
92 self.logger.critical(msg)
94 # logs an exception - use in an except statement
95 def log_exc(self,message):
96 self.error("%s BEG TRACEBACK"%message+"\n"+traceback.format_exc().strip("\n"))
97 self.error("%s END TRACEBACK"%message)
99 def log_exc_critical(self,message):
100 self.critical("%s BEG TRACEBACK"%message+"\n"+traceback.format_exc().strip("\n"))
101 self.critical("%s END TRACEBACK"%message)
103 # for investigation purposes, can be placed anywhere
104 def log_stack(self,message):
105 to_log="".join(traceback.format_stack())
106 self.info("%s BEG STACK"%message+"\n"+to_log)
107 self.info("%s END STACK"%message)
109 def enable_console(self, stream=sys.stdout):
110 formatter = logging.Formatter("%(message)s")
111 handler = logging.StreamHandler(stream)
112 handler.setFormatter(formatter)
113 self.logger.addHandler(handler)
116 info_logger = _SfaLogger(loggername='info', level=logging.INFO)
117 debug_logger = _SfaLogger(loggername='debug', level=logging.DEBUG)
118 warn_logger = _SfaLogger(loggername='warning', level=logging.WARNING)
119 error_logger = _SfaLogger(loggername='error', level=logging.ERROR)
120 critical_logger = _SfaLogger(loggername='critical', level=logging.CRITICAL)
122 sfi_logger = _SfaLogger(logfile=os.path.expanduser("~/.sfi/")+'sfi.log',loggername='sfilog', level=logging.DEBUG)
123 ########################################
128 Prints the runtime of the specified callable. Use as a decorator, e.g.,
134 def logger_profile(callable):
135 def wrapper(*args, **kwds):
137 result = callable(*args, **kwds)
139 args = map(str, args)
140 args += ["%s = %s" % (name, str(value)) for (name, value) in kwds.iteritems()]
141 # should probably use debug, but then debug is not always enabled
142 logger.info("PROFILED %s (%s): %.02f s" % (callable.__name__, ", ".join(args), end - start))
145 return logger_profile
148 if __name__ == '__main__':
149 print 'testing sfalogging into logger.log'
150 logger1=_SfaLogger('logger.log', loggername='std(info)')
151 logger2=_SfaLogger('logger.log', loggername='error', level=logging.ERROR)
152 logger3=_SfaLogger('logger.log', loggername='debug', level=logging.DEBUG)
154 for (logger,msg) in [ (logger1,"std(info)"),(logger2,"error"),(logger3,"debug")]:
156 print "====================",msg, logger.logger.handlers
158 logger.enable_console()
159 logger.critical("logger.critical")
160 logger.error("logger.error")
161 logger.warn("logger.warning")
162 logger.info("logger.info")
163 logger.debug("logger.debug")
164 logger.setLevel(logging.DEBUG)
165 logger.debug("logger.debug again")
168 def sleep(seconds = 1):
171 logger.info('console.info')
173 logger.setLevel(logging.DEBUG)