Tony Mack | ced023a | 2013-06-15 14:32:31 -0400 | [diff] [blame^] | 1 | #!/usr/bin/python |
| 2 | |
| 3 | #---------------------------------------------------------------------- |
| 4 | # Copyright (c) 2008 Board of Trustees, Princeton University |
| 5 | # |
| 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: |
| 12 | # |
| 13 | # The above copyright notice and this permission notice shall be |
| 14 | # included in all copies or substantial portions of the Work. |
| 15 | # |
| 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 |
| 23 | # IN THE WORK. |
| 24 | #---------------------------------------------------------------------- |
| 25 | |
| 26 | import os, sys |
| 27 | import traceback |
| 28 | import logging, logging.handlers |
| 29 | |
| 30 | CRITICAL=logging.CRITICAL |
| 31 | ERROR=logging.ERROR |
| 32 | WARNING=logging.WARNING |
| 33 | INFO=logging.INFO |
| 34 | DEBUG=logging.DEBUG |
| 35 | |
| 36 | # a logger that can handle tracebacks |
| 37 | class Logger: |
| 38 | def __init__ (self,logfile=None,loggername=None,level=logging.INFO): |
| 39 | # default is to locate loggername from the logfile if avail. |
| 40 | if not logfile: |
| 41 | #loggername='console' |
| 42 | #handler=logging.StreamHandler() |
| 43 | #handler.setFormatter(logging.Formatter("%(levelname)s %(message)s")) |
| 44 | logfile = "/var/log/planetstack.log" |
| 45 | |
| 46 | if not loggername: |
| 47 | loggername=os.path.basename(logfile) |
| 48 | try: |
| 49 | handler=logging.handlers.RotatingFileHandler(logfile,maxBytes=1000000, backupCount=5) |
| 50 | except IOError: |
| 51 | # This is usually a permissions error becaue the file is |
| 52 | # owned by root, but httpd is trying to access it. |
| 53 | tmplogfile=os.getenv("TMPDIR", "/tmp") + os.path.sep + os.path.basename(logfile) |
| 54 | # In strange uses, 2 users on same machine might use same code, |
| 55 | # meaning they would clobber each others files |
| 56 | # We could (a) rename the tmplogfile, or (b) |
| 57 | # just log to the console in that case. |
| 58 | # Here we default to the console. |
| 59 | if os.path.exists(tmplogfile) and not os.access(tmplogfile,os.W_OK): |
| 60 | loggername = loggername + "-console" |
| 61 | handler = logging.StreamHandler() |
| 62 | else: |
| 63 | handler=logging.handlers.RotatingFileHandler(tmplogfile,maxBytes=1000000, backupCount=5) |
| 64 | handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")) |
| 65 | self.logger=logging.getLogger(loggername) |
| 66 | self.logger.setLevel(level) |
| 67 | # check if logger already has the handler we're about to add |
| 68 | handler_exists = False |
| 69 | for l_handler in self.logger.handlers: |
| 70 | if l_handler.baseFilename == handler.baseFilename and \ |
| 71 | l_handler.level == handler.level: |
| 72 | handler_exists = True |
| 73 | |
| 74 | if not handler_exists: |
| 75 | self.logger.addHandler(handler) |
| 76 | |
| 77 | self.loggername=loggername |
| 78 | |
| 79 | def setLevel(self,level): |
| 80 | self.logger.setLevel(level) |
| 81 | |
| 82 | # shorthand to avoid having to import logging all over the place |
| 83 | def setLevelDebug(self): |
| 84 | self.logger.setLevel(logging.DEBUG) |
| 85 | |
| 86 | def debugEnabled (self): |
| 87 | return self.logger.getEffectiveLevel() == logging.DEBUG |
| 88 | |
| 89 | # define a verbose option with s/t like |
| 90 | # parser.add_option("-v", "--verbose", action="count", dest="verbose", default=0) |
| 91 | # and pass the coresponding options.verbose to this method to adjust level |
| 92 | def setLevelFromOptVerbose(self,verbose): |
| 93 | if verbose==0: |
| 94 | self.logger.setLevel(logging.WARNING) |
| 95 | elif verbose==1: |
| 96 | self.logger.setLevel(logging.INFO) |
| 97 | elif verbose>=2: |
| 98 | self.logger.setLevel(logging.DEBUG) |
| 99 | # in case some other code needs a boolean |
| 100 | def getBoolVerboseFromOpt(self,verbose): |
| 101 | return verbose>=1 |
| 102 | def getBoolDebugFromOpt(self,verbose): |
| 103 | return verbose>=2 |
| 104 | |
| 105 | #################### |
| 106 | def info(self, msg): |
| 107 | self.logger.info(msg) |
| 108 | |
| 109 | def debug(self, msg): |
| 110 | self.logger.debug(msg) |
| 111 | |
| 112 | def warn(self, msg): |
| 113 | self.logger.warn(msg) |
| 114 | |
| 115 | # some code is using logger.warn(), some is using logger.warning() |
| 116 | def warning(self, msg): |
| 117 | self.logger.warning(msg) |
| 118 | |
| 119 | def error(self, msg): |
| 120 | self.logger.error(msg) |
| 121 | |
| 122 | def critical(self, msg): |
| 123 | self.logger.critical(msg) |
| 124 | |
| 125 | # logs an exception - use in an except statement |
| 126 | def log_exc(self,message): |
| 127 | self.error("%s BEG TRACEBACK"%message+"\n"+traceback.format_exc().strip("\n")) |
| 128 | self.error("%s END TRACEBACK"%message) |
| 129 | |
| 130 | def log_exc_critical(self,message): |
| 131 | self.critical("%s BEG TRACEBACK"%message+"\n"+traceback.format_exc().strip("\n")) |
| 132 | self.critical("%s END TRACEBACK"%message) |
| 133 | |
| 134 | # for investigation purposes, can be placed anywhere |
| 135 | def log_stack(self,message): |
| 136 | to_log="".join(traceback.format_stack()) |
| 137 | self.info("%s BEG STACK"%message+"\n"+to_log) |
| 138 | self.info("%s END STACK"%message) |
| 139 | |
| 140 | def enable_console(self, stream=sys.stdout): |
| 141 | formatter = logging.Formatter("%(message)s") |
| 142 | handler = logging.StreamHandler(stream) |
| 143 | handler.setFormatter(formatter) |
| 144 | self.logger.addHandler(handler) |
| 145 | |
| 146 | |
| 147 | info_logger = Logger(loggername='info', level=logging.INFO) |
| 148 | debug_logger = Logger(loggername='debug', level=logging.DEBUG) |
| 149 | warn_logger = Logger(loggername='warning', level=logging.WARNING) |
| 150 | error_logger = Logger(loggername='error', level=logging.ERROR) |
| 151 | critical_logger = Logger(loggername='critical', level=logging.CRITICAL) |
| 152 | logger = info_logger |
| 153 | ######################################## |
| 154 | import time |
| 155 | |
| 156 | def profile(logger): |
| 157 | """ |
| 158 | Prints the runtime of the specified callable. Use as a decorator, e.g., |
| 159 | |
| 160 | @profile(logger) |
| 161 | def foo(...): |
| 162 | ... |
| 163 | """ |
| 164 | def logger_profile(callable): |
| 165 | def wrapper(*args, **kwds): |
| 166 | start = time.time() |
| 167 | result = callable(*args, **kwds) |
| 168 | end = time.time() |
| 169 | args = map(str, args) |
| 170 | args += ["%s = %s" % (name, str(value)) for (name, value) in kwds.iteritems()] |
| 171 | # should probably use debug, but then debug is not always enabled |
| 172 | logger.info("PROFILED %s (%s): %.02f s" % (callable.__name__, ", ".join(args), end - start)) |
| 173 | return result |
| 174 | return wrapper |
| 175 | return logger_profile |
| 176 | |
| 177 | |
| 178 | if __name__ == '__main__': |
| 179 | print 'testing logging into logger.log' |
| 180 | logger1=Logger('logger.log', loggername='std(info)') |
| 181 | logger2=Logger('logger.log', loggername='error', level=logging.ERROR) |
| 182 | logger3=Logger('logger.log', loggername='debug', level=logging.DEBUG) |
| 183 | |
| 184 | for (logger,msg) in [ (logger1,"std(info)"),(logger2,"error"),(logger3,"debug")]: |
| 185 | |
| 186 | print "====================",msg, logger.logger.handlers |
| 187 | |
| 188 | logger.enable_console() |
| 189 | logger.critical("logger.critical") |
| 190 | logger.error("logger.error") |
| 191 | logger.warn("logger.warning") |
| 192 | logger.info("logger.info") |
| 193 | logger.debug("logger.debug") |
| 194 | logger.setLevel(logging.DEBUG) |
| 195 | logger.debug("logger.debug again") |
| 196 | |
| 197 | @profile(logger) |
| 198 | def sleep(seconds = 1): |
| 199 | time.sleep(seconds) |
| 200 | |
| 201 | logger.info('console.info') |
| 202 | sleep(0.5) |
| 203 | logger.setLevel(logging.DEBUG) |
| 204 | sleep(0.25) |
| 205 | |