minor and harmless cosmetic changes
[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 logger = _SfaLogger(loggername='info', level=logging.INFO)
170
171 sfi_logger = _SfaLogger(logfile=os.path.expanduser("~/.sfi/") + 'sfi.log',
172                         loggername='sfilog', level=logging.DEBUG)
173 ########################################
174 import time
175
176
177 def profile(logger):
178     """
179     Prints the runtime of the specified callable. Use as a decorator, e.g.,
180
181     @profile(logger)
182     def foo(...):
183         ...
184     """
185     def logger_profile(callable):
186         def wrapper(*args, **kwds):
187             start = time.time()
188             result = callable(*args, **kwds)
189             end = time.time()
190             args = map(str, args)
191             args += ["%s = %s" % (name, str(value))
192                      for (name, value) in kwds.iteritems()]
193             # should probably use debug, but then debug is not always enabled
194             logger.info("PROFILED %s (%s): %.02f s" %
195                         (callable.__name__, ", ".join(args), end - start))
196             return result
197         return wrapper
198     return logger_profile
199
200
201 if __name__ == '__main__':
202     print('testing sfalogging into logger.log')
203     logger1 = _SfaLogger('logger.log', loggername='std(info)')
204     logger2 = _SfaLogger('logger.log', loggername='error', level=logging.ERROR)
205     logger3 = _SfaLogger('logger.log', loggername='debug', level=logging.DEBUG)
206
207     for logger, msg in ((logger1, "std(info)"), (logger2, "error"), (logger3, "debug")):
208
209         print("====================", msg, logger.logger.handlers)
210
211         logger.enable_console()
212         logger.critical("logger.critical")
213         logger.error("logger.error")
214         logger.warn("logger.warning")
215         logger.info("logger.info")
216         logger.debug("logger.debug")
217         logger.setLevel(logging.DEBUG)
218         logger.debug("logger.debug again")
219
220         @profile(logger)
221         def sleep(seconds=1):
222             time.sleep(seconds)
223
224         logger.info('console.info')
225         sleep(0.5)
226         logger.setLevel(logging.DEBUG)
227         sleep(0.25)