Python 7.0pl5 Benutzerhandbuch

Seite von 124
Logging Facility
16
Specifying a Log Channel
When logging a message, a log channel may also be specified. If the name of a log channel starts with
a character other than an alphanumeric character, the message will not be displayed on the standard
error output or appear in the log file. If it is displayed or captured in the log file, the name of the log
channel does not appear anywhere in the message. The intent of the log channel is to allow one part of
an application to capture specific messages produced by another part of the application and deal with
them in a special way.
To log a message against a specific log channel, the member function "
notifyChannel()
" is used.
The name of the log channel is supplied as the first argument.
logger.notifyChannel("VISIBLE",netsvc.LOG_DEBUG,"message")
logger.notifyChannel("#HIDDEN",netsvc.LOG_DEBUG,"message")
Messages logged against a specific log channel, can be captured by calling the member function
"
monitorChannel()
", supplying the name of the log channel and a callback function.
def callback(channel,level,message):
print (channel,level,message)
logger.monitorChannel("#HIDDEN",callback)
The message supplied to the callback function is the original message and does not contain the prefix
describing the priority or level assigned to the message, nor does it contain any details relating to the
current time or process ID. If you are going to subsequently log the message to a file, you would need
to add these details yourself if you require them.
Only one callback can be associated with a particular log channel. If multiple callbacks are required
for a particular log channel, separate instances of the
Logger
class should be used. To stop monitor-
ing a specific log channel, the member function "
monitorChannel()
" is called again but with
"
None
" supplied in place of the callback function.
If the callback function was a member of a class, it is important to deregister the callback, else a refer-
ence to the instance of the class will be maintained and it may not get deleted. You can also deregister
all of the callbacks associated with a particular instance of the
Logger
class by calling the member
function "
destroyReferences()
". This would be necessary if the class containing the callbacks
also held a reference to the instance of the
Logger
class. In this case, a circular reference would exist
and neither object would ever be destroyed.
Logging Python Exceptions
To make the task of logging details of a Python exception easier, the "
logException()
" function
is provided by the "
netsvc
" module. This function should only be called from within the context of
a Python "
except
" clause. The information logged is similar to that displayed by Python when an
exception is not caught and includes details of the exception and a stack trace.