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