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