📄 liblogging.tex
字号:
\subsubsection{NTEventLogHandler}The \class{NTEventLogHandler} class supports sending logging messagesto a local Windows NT, Windows 2000 or Windows XP event log. Beforeyou can use it, you need Mark Hammond's Win32 extensions for Pythoninstalled.\begin{classdesc}{NTEventLogHandler}{appname\optional{, dllname\optional{, logtype}}}Returns a new instance of the \class{NTEventLogHandler} class. The\var{appname} is used to define the application name as it appears in theevent log. An appropriate registry entry is created using this name.The \var{dllname} should give the fully qualified pathname of a .dll or .exewhich contains message definitions to hold in the log (if not specified,\code{'win32service.pyd'} is used - this is installed with the Win32extensions and contains some basic placeholder message definitions.Note that use of these placeholders will make your event logs big, as theentire message source is held in the log. If you want slimmer logs, you haveto pass in the name of your own .dll or .exe which contains the messagedefinitions you want to use in the event log). The \var{logtype} is one of\code{'Application'}, \code{'System'} or \code{'Security'}, anddefaults to \code{'Application'}.\end{classdesc}\begin{methoddesc}{close}{}At this point, you can remove the application name from the registry as asource of event log entries. However, if you do this, you will not be ableto see the events as you intended in the Event Log Viewer - it needs to beable to access the registry to get the .dll name. The current version doesnot do this (in fact it doesn't do anything).\end{methoddesc}\begin{methoddesc}{emit}{record}Determines the message ID, event category and event type, and then logs themessage in the NT event log.\end{methoddesc}\begin{methoddesc}{getEventCategory}{record}Returns the event category for the record. Override this if youwant to specify your own categories. This version returns 0.\end{methoddesc}\begin{methoddesc}{getEventType}{record}Returns the event type for the record. Override this if you wantto specify your own types. This version does a mapping using thehandler's typemap attribute, which is set up in \method{__init__()}to a dictionary which contains mappings for \constant{DEBUG},\constant{INFO}, \constant{WARNING}, \constant{ERROR} and\constant{CRITICAL}. If you are using your own levels, you will either needto override this method or place a suitable dictionary in thehandler's \var{typemap} attribute.\end{methoddesc}\begin{methoddesc}{getMessageID}{record}Returns the message ID for the record. If you are using yourown messages, you could do this by having the \var{msg} passed to thelogger being an ID rather than a format string. Then, in here,you could use a dictionary lookup to get the message ID. Thisversion returns 1, which is the base message ID in\file{win32service.pyd}.\end{methoddesc}\subsubsection{SMTPHandler}The \class{SMTPHandler} class supports sending logging messages to an emailaddress via SMTP.\begin{classdesc}{SMTPHandler}{mailhost, fromaddr, toaddrs, subject}Returns a new instance of the \class{SMTPHandler} class. Theinstance is initialized with the from and to addresses and subjectline of the email. The \var{toaddrs} should be a list of strings withoutdomain names (That's what the \var{mailhost} is for). To specify anon-standard SMTP port, use the (host, port) tuple format for the\var{mailhost} argument. If you use a string, the standard SMTP portis used.\end{classdesc}\begin{methoddesc}{emit}{record}Formats the record and sends it to the specified addressees.\end{methoddesc}\begin{methoddesc}{getSubject}{record}If you want to specify a subject line which is record-dependent,override this method.\end{methoddesc}\subsubsection{MemoryHandler}The \class{MemoryHandler} supports buffering of logging records in memory,periodically flushing them to a \dfn{target} handler. Flushing occurswhenever the buffer is full, or when an event of a certain severity orgreater is seen.\class{MemoryHandler} is a subclass of the more general\class{BufferingHandler}, which is an abstract class. This buffers loggingrecords in memory. Whenever each record is added to the buffer, acheck is made by calling \method{shouldFlush()} to see if the buffershould be flushed. If it should, then \method{flush()} is expected todo the needful.\begin{classdesc}{BufferingHandler}{capacity}Initializes the handler with a buffer of the specified capacity.\end{classdesc}\begin{methoddesc}{emit}{record}Appends the record to the buffer. If \method{shouldFlush()} returns true,calls \method{flush()} to process the buffer.\end{methoddesc}\begin{methoddesc}{flush}{}You can override this to implement custom flushing behavior. This versionjust zaps the buffer to empty.\end{methoddesc}\begin{methoddesc}{shouldFlush}{record}Returns true if the buffer is up to capacity. This method can beoverridden to implement custom flushing strategies.\end{methoddesc}\begin{classdesc}{MemoryHandler}{capacity\optional{, flushLevel\optional{, target}}}Returns a new instance of the \class{MemoryHandler} class. Theinstance is initialized with a buffer size of \var{capacity}. If\var{flushLevel} is not specified, \constant{ERROR} is used. If no\var{target} is specified, the target will need to be set using\method{setTarget()} before this handler does anything useful.\end{classdesc}\begin{methoddesc}{close}{}Calls \method{flush()}, sets the target to \constant{None} andclears the buffer.\end{methoddesc}\begin{methoddesc}{flush}{}For a \class{MemoryHandler}, flushing means just sending the bufferedrecords to the target, if there is one. Override if you wantdifferent behavior.\end{methoddesc}\begin{methoddesc}{setTarget}{target}Sets the target handler for this handler.\end{methoddesc}\begin{methoddesc}{shouldFlush}{record}Checks for buffer full or a record at the \var{flushLevel} or higher.\end{methoddesc}\subsubsection{HTTPHandler}The \class{HTTPHandler} class supports sending logging messages to aWeb server, using either \samp{GET} or \samp{POST} semantics.\begin{classdesc}{HTTPHandler}{host, url\optional{, method}}Returns a new instance of the \class{HTTPHandler} class. Theinstance is initialized with a host address, url and HTTP method.If no \var{method} is specified, \samp{GET} is used.\end{classdesc}\begin{methoddesc}{emit}{record}Sends the record to the Web server as an URL-encoded dictionary.\end{methoddesc}\subsection{Formatter Objects}\class{Formatter}s have the following attributes and methods. They areresponsible for converting a \class{LogRecord} to (usually) a stringwhich can be interpreted by either a human or an external system. Thebase\class{Formatter} allows a formatting string to be specified. If none issupplied, the default value of \code{'\%(message)s\e'} is used.A Formatter can be initialized with a format string which makes use ofknowledge of the \class{LogRecord} attributes - such as the default valuementioned above making use of the fact that the user's message andarguments are pre-formatted into a LogRecord's \var{message}attribute. This format string contains standard python \%-stylemapping keys. See section \ref{typesseq-strings}, ``String FormattingOperations,'' for more information on string formatting.Currently, the useful mapping keys in a LogRecord are:\begin{tableii}{l|l}{code}{Format}{Description}\lineii{\%(name)s} {Name of the logger (logging channel).}\lineii{\%(levelno)s} {Numeric logging level for the message (\constant{DEBUG}, \constant{INFO}, \constant{WARNING}, \constant{ERROR}, \constant{CRITICAL}).}\lineii{\%(levelname)s}{Text logging level for the message (\code{'DEBUG'}, \code{'INFO'}, \code{'WARNING'}, \code{'ERROR'}, \code{'CRITICAL'}).}\lineii{\%(pathname)s} {Full pathname of the source file where the logging call was issued (if available).}\lineii{\%(filename)s} {Filename portion of pathname.}\lineii{\%(module)s} {Module (name portion of filename).}\lineii{\%(lineno)d} {Source line number where the logging call was issued (if available).}\lineii{\%(created)f} {Time when the LogRecord was created (as returned by \function{time.time()}).}\lineii{\%(asctime)s} {Human-readable time when the LogRecord was created. By default this is of the form ``2003-07-08 16:49:45,896'' (the numbers after the comma are millisecond portion of the time).}\lineii{\%(msecs)d} {Millisecond portion of the time when the \class{LogRecord} was created.}\lineii{\%(thread)d} {Thread ID (if available).}\lineii{\%(process)d} {Process ID (if available).}\lineii{\%(message)s} {The logged message, computed as \code{msg \% args}.}\end{tableii}\begin{classdesc}{Formatter}{\optional{fmt\optional{, datefmt}}}Returns a new instance of the \class{Formatter} class. Theinstance is initialized with a format string for the message as a whole,as well as a format string for the date/time portion of a message. Ifno \var{fmt} is specified, \code{'\%(message)s'} is used. If no \var{datefmt}is specified, the ISO8601 date format is used.\end{classdesc}\begin{methoddesc}{format}{record}The record's attribute dictionary is used as the operand to astring formatting operation. Returns the resulting string.Before formatting the dictionary, a couple of preparatory stepsare carried out. The \var{message} attribute of the record is computedusing \var{msg} \% \var{args}. If the formatting string contains\code{'(asctime)'}, \method{formatTime()} is called to format theevent time. If there is exception information, it is formatted using\method{formatException()} and appended to the message.\end{methoddesc}\begin{methoddesc}{formatTime}{record\optional{, datefmt}}This method should be called from \method{format()} by a formatter whichwants to make use of a formatted time. This method can be overriddenin formatters to provide for any specific requirement, but thebasic behavior is as follows: if \var{datefmt} (a string) is specified,it is used with \function{time.strftime()} to format the creation time of therecord. Otherwise, the ISO8601 format is used. The resultingstring is returned.\end{methoddesc}\begin{methoddesc}{formatException}{exc_info}Formats the specified exception information (a standard exception tupleas returned by \function{sys.exc_info()}) as a string. This defaultimplementation just uses \function{traceback.print_exception()}.The resulting string is returned.\end{methoddesc}\subsection{Filter Objects}\class{Filter}s can be used by \class{Handler}s and \class{Logger}s formore sophisticated filtering than is provided by levels. The base filterclass only allows events which are below a certain point in the loggerhierarchy. For example, a filter initialized with "A.B" will allow eventslogged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB","B.A.B" etc. If initialized with the empty string, all events are passed.\begin{classdesc}{Filter}{\optional{name}}Returns an instance of the \class{Filter} class. If \var{name} is specified,it names a logger which, together with its children, will have its eventsallowed through the filter. If no name is specified, allows every event.\end{classdesc}\begin{methoddesc}{filter}{record}Is the specified record to be logged? Returns zero for no, nonzero foryes. If deemed appropriate, the record may be modified in-place by thismethod.\end{methoddesc}\subsection{LogRecord Objects}LogRecord instances are created every time something is logged. Theycontain all the information pertinent to the event being logged. Themain information passed in is in msg and args, which are combinedusing msg \% args to create the message field of the record. The recordalso includes information such as when the record was created, thesource line where the logging call was made, and any exceptioninformation to be logged.LogRecord has no methods; it's just a repository for information about thelogging event. The only reason it's a class rather than a dictionary is tofacilitate extension.\begin{classdesc}{LogRecord}{name, lvl, pathname, lineno, msg, args, exc_info}Returns an instance of \class{LogRecord} initialized with interestinginformation. The \var{name} is the logger name; \var{lvl} is thenumeric level; \var{pathname} is the absolute pathname of the sourcefile in which the logging call was made; \var{lineno} is the linenumber in that file where the logging call is found; \var{msg} is theuser-supplied message (a format string); \var{args} is the tuplewhich, together with \var{msg}, makes up the user message; and\var{exc_info} is the exception tuple obtained by calling\function{sys.exc_info() }(or \constant{None}, if no exception informationis available).\end{classdesc}\subsection{Thread Safety}The logging module is intended to be thread-safe without any special workneeding to be done by its clients. It achieves this though using threadinglocks; there is one lock to serialize access to the module's shared data,and each handler also creates a lock to serialize access to its underlyingI/O.\subsection{Configuration}\subsubsection{Configuration functions}The following functions allow the logging module to beconfigured. Before they can be used, you must import\module{logging.config}. Their use is optional --- you can configurethe logging module entirely by making calls to the main API (definedin \module{logging} itself) and defining handlers which are declaredeither in \module{logging} or \module{logging.handlers}.\begin{funcdesc}{fileConfig}{fname\optional{, defaults}}Reads the logging configuration from a ConfigParser-format file named\var{fname}. This function can be called several times from an application,allowing an end user the ability to select from various pre-cannedconfigurations (if the developer provides a mechanism to present thechoices and load the chosen configuration). Defaults to be passed to
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -