Skip to content

Commit

Permalink
SF patch #687683, Patches to logging (updates from Vinay)
Browse files Browse the repository at this point in the history
Mostly rename WARN -> WARNING
Other misc tweaks
Update tests (not in original patch)
  • Loading branch information
nnorwitz committed Feb 18, 2003
1 parent d6a3f93 commit 6fa635d
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 63 deletions.
21 changes: 11 additions & 10 deletions Doc/lib/liblogging.tex
Original file line number Diff line number Diff line change
Expand Up @@ -250,8 +250,9 @@ \subsection{Logger Objects}
\begin{methoddesc}{setLevel}{lvl}
Sets the threshold for this logger to \var{lvl}. Logging messages
which are less severe than \var{lvl} will be ignored. When a logger is
created, the level is set to \constant{ALL} (which causes all messages
to be processed).
created, the level is set to \constant{NOTSET} (which causes all messages
to be processed in the root logger, or delegation to the parent in non-root
loggers).
\end{methoddesc}

\begin{methoddesc}{isEnabledFor}{lvl}
Expand All @@ -263,9 +264,9 @@ \subsection{Logger Objects}

\begin{methoddesc}{getEffectiveLevel}{}
Indicates the effective level for this logger. If a value other than
\constant{ALL} has been set using \method{setLevel()}, it is returned.
\constant{NOTSET} has been set using \method{setLevel()}, it is returned.
Otherwise, the hierarchy is traversed towards the root until a value
other than \constant{ALL} is found, and that value is returned.
other than \constant{NOTSET} is found,and that value is returned.
\end{methoddesc}

\begin{methoddesc}{debug}{msg\optional{, *args\optional{, **kwargs}}}
Expand Down Expand Up @@ -355,7 +356,7 @@ \subsection{Handler Objects}
base for more useful subclasses. However, the \method{__init__()}
method in subclasses needs to call \method{Handler.__init__()}.

\begin{methoddesc}{__init__}{level=\constant{ALL}}
\begin{methoddesc}{__init__}{level=\constant{NOTSET}}
Initializes the \class{Handler} instance by setting its level, setting
the list of filters to the empty list and creating a lock (using
\method{getLock()}) for serializing access to an I/O mechanism.
Expand All @@ -377,7 +378,7 @@ \subsection{Handler Objects}
\begin{methoddesc}{setLevel}{lvl}
Sets the threshold for this handler to \var{lvl}. Logging messages which are
less severe than \var{lvl} will be ignored. When a handler is created, the
level is set to \constant{ALL} (which causes all messages to be processed).
level is set to \constant{NOTSET} (which causes all messages to be processed).
\end{methoddesc}

\begin{methoddesc}{setFormatter}{form}
Expand Down Expand Up @@ -487,7 +488,7 @@ \subsubsection{RotatingFileHandler}
The \class{RotatingFileHandler} class supports rotation of disk log files.

\begin{classdesc}{RotatingFileHandler}{filename\optional{, mode, maxBytes,
backupCount}}
backupCount}}
Returns a new instance of the \class{RotatingFileHandler} class. The
specified file is opened and used as the stream for logging. If
\var{mode} is not specified, \code{'a'} is used. By default, the
Expand Down Expand Up @@ -736,7 +737,7 @@ \subsubsection{MemoryHandler}
\end{methoddesc}

\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel
\optional{, target}}}
\optional{, target}}}
Returns a new instance of the \class{MemoryHandler} class. The
instance is initialized with a buffer size of \var{capacity}. If
\var{flushLevel} is not specified, \constant{ERROR} is used. If no
Expand Down Expand Up @@ -813,10 +814,10 @@ \subsection{Formatter Objects}
relative to the time the logging module was loaded
(typically at application startup time)
\%(thread)d Thread ID (if available)
\%(process)d Process ID (if available)
\%(message)s The result of msg \% args, computed just as the
record is emitted


\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}
Returns a new instance of the \class{Formatter} class. The
instance is initialized with a format string for the message as a whole,
Expand Down Expand Up @@ -889,7 +890,7 @@ \subsection{LogRecord Objects}
facilitate extension.

\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args,
exc_info}
exc_info}
Returns an instance of \class{LogRecord} initialized with interesting
information. The \var{name} is the logger name; \var{lvl} is the
numeric level; \var{pathname} is the absolute pathname of the source
Expand Down
86 changes: 58 additions & 28 deletions Lib/logging/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,24 @@

__author__ = "Vinay Sajip <vinay_sajip@red-dove.com>"
__status__ = "alpha"
__version__ = "0.4.7"
__date__ = "27 August 2002"
__version__ = "0.4.8"
__date__ = "16 February 2003"

#---------------------------------------------------------------------------
# Miscellaneous module data
#---------------------------------------------------------------------------

#
# _verinfo is used for when behaviour needs to be adjusted to the version
# of Python
#

_verinfo = getattr(sys, "version_info", None)

#
#_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']:
_srcfile = __file__[:-4] + '.py'
else:
Expand All @@ -70,7 +78,6 @@
#
raiseExceptions = 1


#---------------------------------------------------------------------------
# Level related stuff
#---------------------------------------------------------------------------
Expand All @@ -84,21 +91,23 @@
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARN = 30
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

_levelNames = {
CRITICAL : 'CRITICAL',
ERROR : 'ERROR',
WARN : 'WARN',
WARNING : 'WARNING',
INFO : 'INFO',
DEBUG : 'DEBUG',
NOTSET : 'NOTSET',
'CRITICAL' : CRITICAL,
'ERROR' : ERROR,
'WARN' : WARN,
'WARN' : WARNING,
'WARNING' : WARNING,
'INFO' : INFO,
'DEBUG' : DEBUG,
'NOTSET' : NOTSET,
Expand All @@ -108,7 +117,7 @@ def getLevelName(level):
"""
Return the textual representation of logging level 'level'.
If the level is one of the predefined levels (CRITICAL, ERROR, WARN,
If the level is one of the predefined levels (CRITICAL, ERROR, WARNING,
INFO, DEBUG) then you get the corresponding string. If you have
associated levels with names using addLevelName then the name you have
associated with 'level' is returned. Otherwise, the string
Expand Down Expand Up @@ -204,6 +213,7 @@ def __init__(self, name, level, pathname, lineno, msg, args, exc_info):
self.thread = thread.get_ident()
else:
self.thread = None
self.process = os.getpid()

def __str__(self):
return '<LogRecord: %s, %s, %s, %s, "%s">'%(self.name, self.levelno,
Expand All @@ -216,7 +226,13 @@ def getMessage(self):
Return the message for this LogRecord after merging any user-supplied
arguments with the message.
"""
msg = str(self.msg)
if not hasattr(types, "UnicodeType"): #if no unicode support...
msg = str(self.msg)
else:
try:
msg = str(self.msg)
except UnicodeError:
msg = self.msg #Defer encoding till later
if self.args:
msg = msg % self.args
return msg
Expand All @@ -243,9 +259,9 @@ class Formatter:
%(name)s Name of the logger (logging channel)
%(levelno)s Numeric logging level for the message (DEBUG, INFO,
WARN, ERROR, CRITICAL)
WARNING, ERROR, CRITICAL)
%(levelname)s Text logging level for the message ("DEBUG", "INFO",
"WARN", "ERROR", "CRITICAL")
"WARNING", "ERROR", "CRITICAL")
%(pathname)s Full pathname of the source file where the logging
call was issued (if available)
%(filename)s Filename portion of pathname
Expand All @@ -260,6 +276,7 @@ class Formatter:
relative to the time the logging module was loaded
(typically at application startup time)
%(thread)d Thread ID (if available)
%(process)d Process ID (if available)
%(message)s The result of record.getMessage(), computed just as
the record is emitted
"""
Expand Down Expand Up @@ -558,14 +575,17 @@ def handle(self, record):
Emission depends on filters which may have been added to the handler.
Wrap the actual emission of the record with acquisition/release of
the I/O thread lock.
the I/O thread lock. Returns whether the filter passed the record for
emission.
"""
if self.filter(record):
rv = self.filter(record)
if rv:
self.acquire()
try:
self.emit(record)
finally:
self.release()
return rv

def setFormatter(self, fmt):
"""
Expand All @@ -591,17 +611,17 @@ def close(self):
"""
pass

def handleError(self):
def handleError(self, record):
"""
Handle errors which occur during an emit() call.
This method should be called from handlers when an exception is
encountered during an emit() call. By default it does nothing,
because by default raiseExceptions is false, which means that
encountered during an emit() call. If raiseExceptions is false,
exceptions get silently ignored. This is what is mostly wanted
for a logging system - most users will not care about errors in
the logging system, they are more interested in application errors.
You could, however, replace this with a custom handler if you wish.
The record which was being processed is passed in to this method.
"""
if raiseExceptions:
import traceback
Expand Down Expand Up @@ -645,10 +665,16 @@ def emit(self, record):
"""
try:
msg = self.format(record)
self.stream.write("%s\n" % msg)
if not hasattr(types, "UnicodeType"): #if no unicode support...
self.stream.write("%s\n" % msg)
else:
try:
self.stream.write("%s\n" % msg)
except UnicodeError:
self.stream.write("%s\n" % msg.encode("UTF-8"))
self.flush()
except:
self.handleError()
self.handleError(record)

class FileHandler(StreamHandler):
"""
Expand Down Expand Up @@ -861,19 +887,21 @@ def info(self, msg, *args, **kwargs):
if INFO >= self.getEffectiveLevel():
apply(self._log, (INFO, msg, args), kwargs)

def warn(self, msg, *args, **kwargs):
def warning(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'WARN'.
Log 'msg % args' with severity 'WARNING'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.warn("Houston, we have a %s", "bit of a problem", exc_info=1)
logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
"""
if self.manager.disable >= WARN:
if self.manager.disable >= WARNING:
return
if self.isEnabledFor(WARN):
apply(self._log, (WARN, msg, args), kwargs)
if self.isEnabledFor(WARNING):
apply(self._log, (WARNING, msg, args), kwargs)

warn = warning

def error(self, msg, *args, **kwargs):
"""
Expand Down Expand Up @@ -982,7 +1010,7 @@ def removeHandler(self, hdlr):
Remove the specified handler from this logger.
"""
if hdlr in self.handlers:
hdlr.close()
#hdlr.close()
self.handlers.remove(hdlr)

def callHandlers(self, record):
Expand Down Expand Up @@ -1047,7 +1075,7 @@ def __init__(self, level):

_loggerClass = Logger

root = RootLogger(WARN)
root = RootLogger(WARNING)
Logger.root = root
Logger.manager = Manager(Logger.root)

Expand Down Expand Up @@ -1119,13 +1147,15 @@ def exception(msg, *args):
"""
apply(error, (msg,)+args, {'exc_info': 1})

def warn(msg, *args, **kwargs):
def warning(msg, *args, **kwargs):
"""
Log a message with severity 'WARN' on the root logger.
Log a message with severity 'WARNING' on the root logger.
"""
if len(root.handlers) == 0:
basicConfig()
apply(root.warn, (msg,)+args, kwargs)
apply(root.warning, (msg,)+args, kwargs)

warn = warning

def info(msg, *args, **kwargs):
"""
Expand Down

0 comments on commit 6fa635d

Please sign in to comment.