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