ac84037d1aac575c0f5e39a472d4db838236c1ce
[sfa.git] / sfa / util / sfalogging.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 _SfaLogger:
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/sfa.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     # define a verbose option with s/t like
87     # parser.add_option("-v", "--verbose", action="count", dest="verbose", default=0)
88     # and pass the coresponding options.verbose to this method to adjust level
89     def setLevelFromOptVerbose(self,verbose):
90         if verbose==0:
91             self.logger.setLevel(logging.WARNING)
92         elif verbose==1:
93             self.logger.setLevel(logging.INFO)
94         elif verbose>=2:
95             self.logger.setLevel(logging.DEBUG)
96     # in case some other code needs a boolean
97     def getBoolVerboseFromOpt(self,verbose):
98         return verbose>=1
99
100     ####################
101     def info(self, msg):
102         self.logger.info(msg)
103
104     def debug(self, msg):
105         self.logger.debug(msg)
106         
107     def warn(self, msg):
108         self.logger.warn(msg)
109
110     # some code is using logger.warn(), some is using logger.warning()
111     def warning(self, msg):
112         self.logger.warning(msg)
113    
114     def error(self, msg):
115         self.logger.error(msg)    
116  
117     def critical(self, msg):
118         self.logger.critical(msg)
119
120     # logs an exception - use in an except statement
121     def log_exc(self,message):
122         self.error("%s BEG TRACEBACK"%message+"\n"+traceback.format_exc().strip("\n"))
123         self.error("%s END TRACEBACK"%message)
124     
125     def log_exc_critical(self,message):
126         self.critical("%s BEG TRACEBACK"%message+"\n"+traceback.format_exc().strip("\n"))
127         self.critical("%s END TRACEBACK"%message)
128     
129     # for investigation purposes, can be placed anywhere
130     def log_stack(self,message):
131         to_log="".join(traceback.format_stack())
132         self.info("%s BEG STACK"%message+"\n"+to_log)
133         self.info("%s END STACK"%message)
134
135     def enable_console(self, stream=sys.stdout):
136         formatter = logging.Formatter("%(message)s")
137         handler = logging.StreamHandler(stream)
138         handler.setFormatter(formatter)
139         self.logger.addHandler(handler)
140
141
142 info_logger = _SfaLogger(loggername='info', level=logging.INFO)
143 debug_logger = _SfaLogger(loggername='debug', level=logging.DEBUG)
144 warn_logger = _SfaLogger(loggername='warning', level=logging.WARNING)
145 error_logger = _SfaLogger(loggername='error', level=logging.ERROR)
146 critical_logger = _SfaLogger(loggername='critical', level=logging.CRITICAL)
147
148 #sql_logger = _SfaLogger(loggername = 'sqlalchemy.engine', level=logging.DEBUG)
149
150 logger = info_logger
151 sfi_logger = _SfaLogger(logfile=os.path.expanduser("~/.sfi/")+'sfi.log',loggername='sfilog', level=logging.DEBUG)
152 ########################################
153 import time
154
155 def profile(logger):
156     """
157     Prints the runtime of the specified callable. Use as a decorator, e.g.,
158     
159     @profile(logger)
160     def foo(...):
161         ...
162     """
163     def logger_profile(callable):
164         def wrapper(*args, **kwds):
165             start = time.time()
166             result = callable(*args, **kwds)
167             end = time.time()
168             args = map(str, args)
169             args += ["%s = %s" % (name, str(value)) for (name, value) in kwds.iteritems()]
170             # should probably use debug, but then debug is not always enabled
171             logger.info("PROFILED %s (%s): %.02f s" % (callable.__name__, ", ".join(args), end - start))
172             return result
173         return wrapper
174     return logger_profile
175
176
177 if __name__ == '__main__': 
178     print 'testing sfalogging into logger.log'
179     logger1=_SfaLogger('logger.log', loggername='std(info)')
180     logger2=_SfaLogger('logger.log', loggername='error', level=logging.ERROR)
181     logger3=_SfaLogger('logger.log', loggername='debug', level=logging.DEBUG)
182     
183     for (logger,msg) in [ (logger1,"std(info)"),(logger2,"error"),(logger3,"debug")]:
184         
185         print "====================",msg, logger.logger.handlers
186    
187         logger.enable_console()
188         logger.critical("logger.critical")
189         logger.error("logger.error")
190         logger.warn("logger.warning")
191         logger.info("logger.info")
192         logger.debug("logger.debug")
193         logger.setLevel(logging.DEBUG)
194         logger.debug("logger.debug again")
195     
196         @profile(logger)
197         def sleep(seconds = 1):
198             time.sleep(seconds)
199
200         logger.info('console.info')
201         sleep(0.5)
202         logger.setLevel(logging.DEBUG)
203         sleep(0.25)
204