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