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