0610d4bfe5e53880d7c31be75ab94fce419ed69a
[plstackapi.git] / planetstack / util / logger.py
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
45             try:
46                 from planetstack.config import Config
47                 logfile = Config().observer_log_file
48             except:
49                 logfile = "/var/log/planetstack.log"
50
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         handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
70         self.logger=logging.getLogger(loggername)
71         self.logger.setLevel(level)
72         # check if logger already has the handler we're about to add
73         handler_exists = False
74         for l_handler in self.logger.handlers:
75             if l_handler.baseFilename == handler.baseFilename and \
76                l_handler.level == handler.level:
77                 handler_exists = True 
78
79         if not handler_exists:
80             self.logger.addHandler(handler)
81
82         self.loggername=loggername
83
84     def setLevel(self,level):
85         self.logger.setLevel(level)
86
87     # shorthand to avoid having to import logging all over the place
88     def setLevelDebug(self):
89         self.logger.setLevel(logging.DEBUG)
90
91     def debugEnabled (self):
92         return self.logger.getEffectiveLevel() == logging.DEBUG
93
94     # define a verbose option with s/t like
95     # parser.add_option("-v", "--verbose", action="count", dest="verbose", default=0)
96     # and pass the coresponding options.verbose to this method to adjust level
97     def setLevelFromOptVerbose(self,verbose):
98         if verbose==0:
99             self.logger.setLevel(logging.WARNING)
100         elif verbose==1:
101             self.logger.setLevel(logging.INFO)
102         elif verbose>=2:
103             self.logger.setLevel(logging.DEBUG)
104     # in case some other code needs a boolean
105     def getBoolVerboseFromOpt(self,verbose):
106         return verbose>=1
107     def getBoolDebugFromOpt(self,verbose):
108         return verbose>=2
109
110     ####################
111     def info(self, msg):
112         self.logger.info(msg)
113
114     def debug(self, msg):
115         self.logger.debug(msg)
116         
117     def warn(self, msg):
118         self.logger.warn(msg)
119
120     # some code is using logger.warn(), some is using logger.warning()
121     def warning(self, msg):
122         self.logger.warning(msg)
123    
124     def error(self, msg):
125         self.logger.error(msg)    
126  
127     def critical(self, msg):
128         self.logger.critical(msg)
129
130     # logs an exception - use in an except statement
131     def log_exc(self,message):
132         self.error("%s BEG TRACEBACK"%message+"\n"+traceback.format_exc().strip("\n"))
133         self.error("%s END TRACEBACK"%message)
134     
135     def log_exc_critical(self,message):
136         self.critical("%s BEG TRACEBACK"%message+"\n"+traceback.format_exc().strip("\n"))
137         self.critical("%s END TRACEBACK"%message)
138     
139     # for investigation purposes, can be placed anywhere
140     def log_stack(self,message):
141         to_log="".join(traceback.format_stack())
142         self.info("%s BEG STACK"%message+"\n"+to_log)
143         self.info("%s END STACK"%message)
144
145     def enable_console(self, stream=sys.stdout):
146         formatter = logging.Formatter("%(message)s")
147         handler = logging.StreamHandler(stream)
148         handler.setFormatter(formatter)
149         self.logger.addHandler(handler)
150
151
152 info_logger = Logger(loggername='info', level=logging.INFO)
153 debug_logger = Logger(loggername='debug', level=logging.DEBUG)
154 warn_logger = Logger(loggername='warning', level=logging.WARNING)
155 error_logger = Logger(loggername='error', level=logging.ERROR)
156 critical_logger = Logger(loggername='critical', level=logging.CRITICAL)
157 logger = info_logger
158 ########################################
159 import time
160
161 def profile(logger):
162     """
163     Prints the runtime of the specified callable. Use as a decorator, e.g.,
164     
165     @profile(logger)
166     def foo(...):
167         ...
168     """
169     def logger_profile(callable):
170         def wrapper(*args, **kwds):
171             start = time.time()
172             result = callable(*args, **kwds)
173             end = time.time()
174             args = map(str, args)
175             args += ["%s = %s" % (name, str(value)) for (name, value) in kwds.iteritems()]
176             # should probably use debug, but then debug is not always enabled
177             logger.info("PROFILED %s (%s): %.02f s" % (callable.__name__, ", ".join(args), end - start))
178             return result
179         return wrapper
180     return logger_profile
181
182
183 if __name__ == '__main__': 
184     print 'testing logging into logger.log'
185     logger1=Logger('logger.log', loggername='std(info)')
186     logger2=Logger('logger.log', loggername='error', level=logging.ERROR)
187     logger3=Logger('logger.log', loggername='debug', level=logging.DEBUG)
188     
189     for (logger,msg) in [ (logger1,"std(info)"),(logger2,"error"),(logger3,"debug")]:
190         
191         print "====================",msg, logger.logger.handlers
192    
193         logger.enable_console()
194         logger.critical("logger.critical")
195         logger.error("logger.error")
196         logger.warn("logger.warning")
197         logger.info("logger.info")
198         logger.debug("logger.debug")
199         logger.setLevel(logging.DEBUG)
200         logger.debug("logger.debug again")
201     
202         @profile(logger)
203         def sleep(seconds = 1):
204             time.sleep(seconds)
205
206         logger.info('console.info')
207         sleep(0.5)
208         logger.setLevel(logging.DEBUG)
209         sleep(0.25)
210