[Python-checkins] python/dist/src/Lib/logging __init__.py, 1.24, 1.24.2.1

vsajip at users.sourceforge.net vsajip at users.sourceforge.net
Thu Mar 31 22:10:49 CEST 2005


Update of /cvsroot/python/python/dist/src/Lib/logging
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv17920

Modified Files:
      Tag: release24-maint
	__init__.py 
Log Message:
Misc. changes

Index: __init__.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/logging/__init__.py,v
retrieving revision 1.24
retrieving revision 1.24.2.1
diff -u -d -r1.24 -r1.24.2.1
--- __init__.py	21 Oct 2004 21:24:27 -0000	1.24
+++ __init__.py	31 Mar 2005 20:10:38 -0000	1.24.2.1
@@ -1,4 +1,4 @@
-# Copyright 2001-2004 by Vinay Sajip. All Rights Reserved.
+# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved.
 #
 # Permission to use, copy, modify, and distribute this software and its
 # documentation for any purpose and without fee is hereby granted,
@@ -26,7 +26,12 @@
 To use, simply 'import logging' and log away!
 """
 
-import sys, os, types, time, string, cStringIO
+import sys, os, types, time, string, cStringIO, traceback
+
+try:
+    import codecs
+except ImportError:
+    codecs = None
 
 try:
     import thread
@@ -37,14 +42,14 @@
 __author__  = "Vinay Sajip <vinay_sajip at red-dove.com>"
 __status__  = "beta"
 __version__ = "0.4.9.6"
-__date__    = "20 October 2004"
+__date__    = "27 March 2005"
 
 #---------------------------------------------------------------------------
 #   Miscellaneous module data
 #---------------------------------------------------------------------------
 
 #
-#_srcfile is used when walking the stack to check when we've got the first
+# _srcfile is used when walking the stack to check when we've got the first
 # caller stack frame.
 #
 if string.lower(__file__[-4:]) in ['.pyc', '.pyo']:
@@ -53,12 +58,23 @@
     _srcfile = __file__
 _srcfile = os.path.normcase(_srcfile)
 
+# next bit filched from 1.5.2's inspect.py
+def currentframe():
+    """Return the frame object for the caller's stack frame."""
+    try:
+        raise 'catch me'
+    except:
+        return sys.exc_traceback.tb_frame.f_back
+
+if hasattr(sys, '_getframe'): currentframe = sys._getframe
+# done filching
+
 # _srcfile is only used in conjunction with sys._getframe().
 # To provide compatibility with older versions of Python, set _srcfile
 # to None if _getframe() is not available; this value will prevent
 # findCaller() from being called.
-if not hasattr(sys, "_getframe"):
-    _srcfile = None
+#if not hasattr(sys, "_getframe"):
+#    _srcfile = None
 
 #
 #_startTime is used as the base when calculating the relative time of events
@@ -81,6 +97,7 @@
 # loggers are initialized with NOTSET so that they will log all messages, even
 # at user-defined levels.
 #
+
 CRITICAL = 50
 FATAL = CRITICAL
 ERROR = 40
@@ -224,8 +241,10 @@
         self.relativeCreated = (self.created - _startTime) * 1000
         if thread:
             self.thread = thread.get_ident()
+            self.threadName = threading.currentThread().getName()
         else:
             self.thread = None
+            self.threadName = None
         if hasattr(os, 'getpid'):
             self.process = os.getpid()
         else:
@@ -303,6 +322,7 @@
                         relative to the time the logging module was loaded
                         (typically at application startup time)
     %(thread)d          Thread ID (if available)
+    %(threadName)s      Thread name (if available)
     %(process)d         Process ID (if available)
     %(message)s         The result of record.getMessage(), computed just as
                         the record is emitted
@@ -357,7 +377,6 @@
         This default implementation just uses
         traceback.print_exception()
         """
-        import traceback
         sio = cStringIO.StringIO()
         traceback.print_exception(ei[0], ei[1], ei[2], None, sio)
         s = sio.getvalue()
@@ -554,7 +573,7 @@
         Acquire a thread lock for serializing access to the underlying I/O.
         """
         if thread:
-            self.lock = thread.allocate_lock()
+            self.lock = threading.RLock()
         else:
             self.lock = None
 
@@ -663,7 +682,6 @@
         The record which was being processed is passed in to this method.
         """
         if raiseExceptions:
-            import traceback
             ei = sys.exc_info()
             traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr)
             del ei
@@ -720,11 +738,17 @@
     """
     A handler class which writes formatted logging records to disk files.
     """
-    def __init__(self, filename, mode="a"):
+    def __init__(self, filename, mode='a', encoding=None):
         """
         Open the specified file and use it as the stream for logging.
         """
-        StreamHandler.__init__(self, open(filename, mode))
+        if codecs is None:
+            encoding = None
+        if encoding is None:
+            stream = open(filename, mode)
+        else:
+            stream = codecs.open(filename, mode, encoding)
+        StreamHandler.__init__(self, stream)
         #keep the absolute path, otherwise derived classes which use this
         #may come a cropper when the current directory changes
         self.baseFilename = os.path.abspath(filename)
@@ -1005,16 +1029,16 @@
     def findCaller(self):
         """
         Find the stack frame of the caller so that we can note the source
-        file name and line number.
+        file name, line number and function name.
         """
-        f = sys._getframe(1)
+        f = currentframe().f_back
         while 1:
             co = f.f_code
             filename = os.path.normcase(co.co_filename)
             if filename == _srcfile:
                 f = f.f_back
                 continue
-            return filename, f.f_lineno
+            return filename, f.f_lineno, co.co_name
 
     def makeRecord(self, name, level, fn, lno, msg, args, exc_info):
         """
@@ -1029,9 +1053,9 @@
         all the handlers of this logger to handle the record.
         """
         if _srcfile:
-            fn, lno = self.findCaller()
+            fn, lno, func = self.findCaller()
         else:
-            fn, lno = "<unknown file>", 0
+            fn, lno, func = "(unknown file)", 0, "(unknown function)"
         if exc_info:
             if type(exc_info) != types.TupleType:
                 exc_info = sys.exc_info()
@@ -1153,7 +1177,7 @@
     filename  Specifies that a FileHandler be created, using the specified
               filename, rather than a StreamHandler.
     filemode  Specifies the mode to open the file, if filename is specified
-              (if filemode is unspecified, it defaults to "a").
+              (if filemode is unspecified, it defaults to 'a').
     format    Use the specified format string for the handler.
     datefmt   Use the specified date/time format.
     level     Set the root logger level to the specified level.
@@ -1170,7 +1194,7 @@
     if len(root.handlers) == 0:
         filename = kwargs.get("filename")
         if filename:
-            mode = kwargs.get("filemode", "a")
+            mode = kwargs.get("filemode", 'a')
             hdlr = FileHandler(filename, mode)
         else:
             stream = kwargs.get("stream")



More information about the Python-checkins mailing list