3 #----------------------------------------------------------------------
4 # Copyright (c) 2008 Board of Trustees, Princeton University
6 # Permission is hereby granted, free of charge, to any person obtaining
7 # a copy of this software and/or hardware specification (the "Work") to
8 # deal in the Work without restriction, including without limitation the
9 # rights to use, copy, modify, merge, publish, distribute, sublicense,
10 # and/or sell copies of the Work, and to permit persons to whom the Work
11 # is furnished to do so, subject to the following conditions:
13 # The above copyright notice and this permission notice shall be
14 # included in all copies or substantial portions of the Work.
16 # THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 # OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
24 #----------------------------------------------------------------------
26 from __future__ import print_function
30 import logging, logging.handlers
32 CRITICAL=logging.CRITICAL
34 WARNING=logging.WARNING
38 # a logger that can handle tracebacks
40 def __init__ (self,logfile=None,loggername=None,level=logging.INFO):
41 # default is to locate loggername from the logfile if avail.
44 #handler=logging.StreamHandler()
45 #handler.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
46 logfile = "/var/log/sfa.log"
49 loggername=os.path.basename(logfile)
51 handler=logging.handlers.RotatingFileHandler(logfile,maxBytes=1000000, backupCount=5)
53 # This is usually a permissions error because the file is
54 # owned by root, but httpd is trying to access it.
55 tmplogfile=os.path.join(os.getenv("TMPDIR", os.getenv("TMP", os.path.normpath("/tmp"))), os.path.basename(logfile))
56 tmplogfile = os.path.normpath(tmplogfile)
58 tmpdir = os.path.dirname(tmplogfile)
59 if tmpdir and tmpdir != "" and not os.path.exists(tmpdir):
62 # In strange uses, 2 users on same machine might use same code,
63 # meaning they would clobber each others files
64 # We could (a) rename the tmplogfile, or (b)
65 # just log to the console in that case.
66 # Here we default to the console.
67 if os.path.exists(tmplogfile) and not os.access(tmplogfile,os.W_OK):
68 loggername = loggername + "-console"
69 handler = logging.StreamHandler()
71 handler=logging.handlers.RotatingFileHandler(tmplogfile,maxBytes=1000000, backupCount=5)
72 handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
73 self.logger=logging.getLogger(loggername)
74 self.logger.setLevel(level)
75 # check if logger already has the handler we're about to add
76 handler_exists = False
77 for l_handler in self.logger.handlers:
78 if l_handler.baseFilename == handler.baseFilename and \
79 l_handler.level == handler.level:
82 if not handler_exists:
83 self.logger.addHandler(handler)
85 self.loggername=loggername
87 def setLevel(self,level):
88 self.logger.setLevel(level)
90 # shorthand to avoid having to import logging all over the place
91 def setLevelDebug(self):
92 self.logger.setLevel(logging.DEBUG)
94 def debugEnabled (self):
95 return self.logger.getEffectiveLevel() == logging.DEBUG
97 # define a verbose option with s/t like
98 # parser.add_option("-v", "--verbose", action="count", dest="verbose", default=0)
99 # and pass the coresponding options.verbose to this method to adjust level
100 def setLevelFromOptVerbose(self,verbose):
102 self.logger.setLevel(logging.WARNING)
104 self.logger.setLevel(logging.INFO)
106 self.logger.setLevel(logging.DEBUG)
107 # in case some other code needs a boolean
108 def getBoolVerboseFromOpt(self,verbose):
110 def getBoolDebugFromOpt(self,verbose):
115 self.logger.info(msg)
117 def debug(self, msg):
118 self.logger.debug(msg)
121 self.logger.warn(msg)
123 # some code is using logger.warn(), some is using logger.warning()
124 def warning(self, msg):
125 self.logger.warning(msg)
127 def error(self, msg):
128 self.logger.error(msg)
130 def critical(self, msg):
131 self.logger.critical(msg)
133 # logs an exception - use in an except statement
134 def log_exc(self,message):
135 self.error("%s BEG TRACEBACK"%message+"\n"+traceback.format_exc().strip("\n"))
136 self.error("%s END TRACEBACK"%message)
138 def log_exc_critical(self,message):
139 self.critical("%s BEG TRACEBACK"%message+"\n"+traceback.format_exc().strip("\n"))
140 self.critical("%s END TRACEBACK"%message)
142 # for investigation purposes, can be placed anywhere
143 def log_stack(self,message):
144 to_log="".join(traceback.format_stack())
145 self.info("%s BEG STACK"%message+"\n"+to_log)
146 self.info("%s END STACK"%message)
148 def enable_console(self, stream=sys.stdout):
149 formatter = logging.Formatter("%(message)s")
150 handler = logging.StreamHandler(stream)
151 handler.setFormatter(formatter)
152 self.logger.addHandler(handler)
155 info_logger = _SfaLogger(loggername='info', level=logging.INFO)
156 debug_logger = _SfaLogger(loggername='debug', level=logging.DEBUG)
157 warn_logger = _SfaLogger(loggername='warning', level=logging.WARNING)
158 error_logger = _SfaLogger(loggername='error', level=logging.ERROR)
159 critical_logger = _SfaLogger(loggername='critical', level=logging.CRITICAL)
161 sfi_logger = _SfaLogger(logfile=os.path.expanduser("~/.sfi/")+'sfi.log',loggername='sfilog', level=logging.DEBUG)
162 ########################################
167 Prints the runtime of the specified callable. Use as a decorator, e.g.,
173 def logger_profile(callable):
174 def wrapper(*args, **kwds):
176 result = callable(*args, **kwds)
178 args = map(str, args)
179 args += ["%s = %s" % (name, str(value)) for (name, value) in kwds.iteritems()]
180 # should probably use debug, but then debug is not always enabled
181 logger.info("PROFILED %s (%s): %.02f s" % (callable.__name__, ", ".join(args), end - start))
184 return logger_profile
187 if __name__ == '__main__':
188 print('testing sfalogging into logger.log')
189 logger1=_SfaLogger('logger.log', loggername='std(info)')
190 logger2=_SfaLogger('logger.log', loggername='error', level=logging.ERROR)
191 logger3=_SfaLogger('logger.log', loggername='debug', level=logging.DEBUG)
193 for (logger,msg) in [ (logger1,"std(info)"),(logger2,"error"),(logger3,"debug")]:
195 print("====================",msg, logger.logger.handlers)
197 logger.enable_console()
198 logger.critical("logger.critical")
199 logger.error("logger.error")
200 logger.warn("logger.warning")
201 logger.info("logger.info")
202 logger.debug("logger.debug")
203 logger.setLevel(logging.DEBUG)
204 logger.debug("logger.debug again")
207 def sleep(seconds = 1):
210 logger.info('console.info')
212 logger.setLevel(logging.DEBUG)