[Python-Dev] Re: PEP 282 comments

Vinay Sajip vinay_sajip@red-dove.com
Thu, 21 Mar 2002 23:39:51 -0000


[Jeremy, in response to Guido's YAGNI]
> What's the point here?  I've presented use cases, and I maintain a
> large body of ZODB/ZEO code that already uses these features.  So it
> simply doesn't make sense to say "You Ain't Gonna Need It" because I
> already need it and zLOG already has it.

Okay, we can have our cake and eat it too. (You've gotta love Python.)
Suppose the current module interface stays as it is: debug(), info(),
warn(), error() and fatal() all take (self, msg, *args) as arguments.
exception() has the same arg list but, since it knows it's called in an
exception handling context, it passes sys.exc_info() along. Simple, clean
interface.

Here's log_test10.py, a working example script which shows how easy it is to
roll your own logger.
# -- log_test10.py ---------------------------
import sys
import locale

locale.setlocale(locale.LC_ALL, '')

from logging import *

LOG_FORMAT = "%(asctime)s %(level)-5s %(message)s"
DATE_FORMAT = "%x %X"

class MyLogger(Logger):
 """
 A simple example of a logger extension.
 """
 def debug(self, msg, *args):
  """
  This overridden method passes exception information for DEBUG level calls
  """
  if self.manager.disable >= DEBUG:
   return
  if DEBUG >= self.getChainedPriority():
   ei = sys.exc_info()
   if not ei[1]:
    ei = None
   self._log(DEBUG, msg, args, ei)
   del ei

def config():
 setLoggerClass(MyLogger)
 basicConfig()
 getRootLogger().handlers[0].setFormatter(Formatter(LOG_FORMAT,
DATE_FORMAT))

def run():
 logger = getLogger("mylogger")
 logger.info("Starting...")
 logger.debug("Debug message not in exception handler (no traceback)")
 logger.info("About to throw exception...")
 try:
  print "7" + 4
 except Exception, e:
  logger.debug("Debug message inside exception handler (traceback)")
 logger.info("Done.")
 shutdown()

if __name__ == "__main__":
 config()
 run()
#-- end of log_test10.py ---------------------------
When run, you get...
-- output -------------------------
21/03/02 23:33:04 INFO  Starting...
21/03/02 23:33:05 DEBUG Debug message not in exception handler (no
traceback)
21/03/02 23:33:05 INFO  About to throw exception...
21/03/02 23:33:05 DEBUG Debug message inside exception handler (traceback)
Traceback (innermost last):
  File "log_test10.py", line 45, in run
    print "7" + 4
TypeError: illegal argument type for built-in operation

21/03/02 23:33:05 INFO  Done.
-- output -------------------------

I rest my case (I hope...)

Regards

Vinay