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
32 import logging.handlers
34 CRITICAL = logging.CRITICAL
36 WARNING = logging.WARNING
40 # a logger that can handle tracebacks
45 def __init__(self, logfile=None, loggername=None, level=logging.INFO):
46 # default is to locate loggername from the logfile if avail.
48 # loggername='console'
49 # handler=logging.StreamHandler()
50 #handler.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
51 logfile = "/var/log/sfa.log"
54 loggername = os.path.basename(logfile)
56 handler = logging.handlers.RotatingFileHandler(
57 logfile, maxBytes=1000000, backupCount=5)
59 # This is usually a permissions error because the file is
60 # owned by root, but httpd is trying to access it.
61 tmplogfile = os.path.join(os.getenv("TMPDIR",
62 os.getenv("TMP", os.path.normpath("/tmp"))),
63 os.path.basename(logfile))
64 tmplogfile = os.path.normpath(tmplogfile)
66 tmpdir = os.path.dirname(tmplogfile)
67 if tmpdir and tmpdir != "" and not os.path.exists(tmpdir):
70 # In strange uses, 2 users on same machine might use same code,
71 # meaning they would clobber each others files
72 # We could (a) rename the tmplogfile, or (b)
73 # just log to the console in that case.
74 # Here we default to the console.
75 if os.path.exists(tmplogfile) and not os.access(tmplogfile, os.W_OK):
76 loggername = loggername + "-console"
77 handler = logging.StreamHandler()
79 handler = logging.handlers.RotatingFileHandler(
80 tmplogfile, maxBytes=1000000, backupCount=5)
81 handler.setFormatter(logging.Formatter(
82 "%(asctime)s - %(levelname)s - %(message)s"))
83 self.logger = logging.getLogger(loggername)
84 self.logger.setLevel(level)
85 # check if logger already has the handler we're about to add
86 handler_exists = False
87 for l_handler in self.logger.handlers:
88 if l_handler.baseFilename == handler.baseFilename and \
89 l_handler.level == handler.level:
92 if not handler_exists:
93 self.logger.addHandler(handler)
95 self.loggername = loggername
97 def setLevel(self, level):
98 self.logger.setLevel(level)
100 # shorthand to avoid having to import logging all over the place
101 def setLevelDebug(self):
102 self.logger.setLevel(logging.DEBUG)
104 def debugEnabled(self):
105 return self.logger.getEffectiveLevel() == logging.DEBUG
107 # define a verbose option with s/t like
108 # parser.add_option("-v", "--verbose", action="count", dest="verbose", default=0)
109 # and pass the coresponding options.verbose to this method to adjust level
110 def setLevelFromOptVerbose(self, verbose):
112 self.logger.setLevel(logging.WARNING)
114 self.logger.setLevel(logging.INFO)
116 self.logger.setLevel(logging.DEBUG)
117 # in case some other code needs a boolean
119 def getBoolVerboseFromOpt(self, verbose):
122 def getBoolDebugFromOpt(self, verbose):
127 self.logger.info(msg)
129 def debug(self, msg):
130 self.logger.debug(msg)
133 self.logger.warn(msg)
135 # some code is using logger.warn(), some is using logger.warning()
136 def warning(self, msg):
137 self.logger.warning(msg)
139 def error(self, msg):
140 self.logger.error(msg)
142 def critical(self, msg):
143 self.logger.critical(msg)
145 # logs an exception - use in an except statement
146 def log_exc(self, message):
147 self.error("%s BEG TRACEBACK" % message + "\n" +
148 traceback.format_exc().strip("\n"))
149 self.error("%s END TRACEBACK" % message)
151 def log_exc_critical(self, message):
152 self.critical("%s BEG TRACEBACK" % message + "\n" +
153 traceback.format_exc().strip("\n"))
154 self.critical("%s END TRACEBACK" % message)
156 # for investigation purposes, can be placed anywhere
157 def log_stack(self, message):
158 to_log = "".join(traceback.format_stack())
159 self.info("%s BEG STACK" % message + "\n" + to_log)
160 self.info("%s END STACK" % message)
162 def enable_console(self, stream=sys.stdout):
163 formatter = logging.Formatter("%(message)s")
164 handler = logging.StreamHandler(stream)
165 handler.setFormatter(formatter)
166 self.logger.addHandler(handler)
169 info_logger = _SfaLogger(loggername='info', level=logging.INFO)
170 debug_logger = _SfaLogger(loggername='debug', level=logging.DEBUG)
171 warn_logger = _SfaLogger(loggername='warning', level=logging.WARNING)
172 error_logger = _SfaLogger(loggername='error', level=logging.ERROR)
173 critical_logger = _SfaLogger(loggername='critical', level=logging.CRITICAL)
175 sfi_logger = _SfaLogger(logfile=os.path.expanduser("~/.sfi/") + 'sfi.log',
176 loggername='sfilog', level=logging.DEBUG)
177 ########################################
183 Prints the runtime of the specified callable. Use as a decorator, e.g.,
189 def logger_profile(callable):
190 def wrapper(*args, **kwds):
192 result = callable(*args, **kwds)
194 args = map(str, args)
195 args += ["%s = %s" % (name, str(value))
196 for (name, value) in kwds.iteritems()]
197 # should probably use debug, but then debug is not always enabled
198 logger.info("PROFILED %s (%s): %.02f s" %
199 (callable.__name__, ", ".join(args), end - start))
202 return logger_profile
205 if __name__ == '__main__':
206 print('testing sfalogging into logger.log')
207 logger1 = _SfaLogger('logger.log', loggername='std(info)')
208 logger2 = _SfaLogger('logger.log', loggername='error', level=logging.ERROR)
209 logger3 = _SfaLogger('logger.log', loggername='debug', level=logging.DEBUG)
211 for logger, msg in ((logger1, "std(info)"), (logger2, "error"), (logger3, "debug")):
213 print("====================", msg, logger.logger.handlers)
215 logger.enable_console()
216 logger.critical("logger.critical")
217 logger.error("logger.error")
218 logger.warn("logger.warning")
219 logger.info("logger.info")
220 logger.debug("logger.debug")
221 logger.setLevel(logging.DEBUG)
222 logger.debug("logger.debug again")
225 def sleep(seconds=1):
228 logger.info('console.info')
230 logger.setLevel(logging.DEBUG)