⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 liblogging.tex

📁 xen虚拟机源代码安装包
💻 TEX
📖 第 1 页 / 共 4 页
字号:
ConfigParser can be specified in the \var{defaults} argument.\end{funcdesc}\begin{funcdesc}{listen}{\optional{port}}Starts up a socket server on the specified port, and listens for newconfigurations. If no port is specified, the module's default\constant{DEFAULT_LOGGING_CONFIG_PORT} is used. Logging configurationswill be sent as a file suitable for processing by \function{fileConfig()}.Returns a \class{Thread} instance on which you can call \method{start()}to start the server, and which you can \method{join()} when appropriate.To stop the server, call \function{stopListening()}.\end{funcdesc}\begin{funcdesc}{stopListening}{}Stops the listening server which was created with a call to\function{listen()}. This is typically called before calling \method{join()}on the return value from \function{listen()}.\end{funcdesc}\subsubsection{Configuration file format}The configuration file format understood by \function{fileConfig} isbased on ConfigParser functionality. The file must contain sectionscalled \code{[loggers]}, \code{[handlers]} and \code{[formatters]}which identify by name the entities of each type which are defined inthe file. For each such entity, there is a separate section whichidentified how that entity is configured. Thus, for a logger named\code{log01} in the \code{[loggers]} section, the relevantconfiguration details are held in a section\code{[logger_log01]}. Similarly, a handler called \code{hand01} inthe \code{[handlers]} section will have its configuration held in asection called \code{[handler_hand01]}, while a formatter called\code{form01} in the \code{[formatters]} section will have itsconfiguration specified in a section called\code{[formatter_form01]}. The root logger configuration must bespecified in a section called \code{[logger_root]}.Examples of these sections in the file are given below.\begin{verbatim}[loggers]keys=root,log02,log03,log04,log05,log06,log07[handlers]keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09[formatters]keys=form01,form02,form03,form04,form05,form06,form07,form08,form09\end{verbatim}The root logger must specify a level and a list of handlers. Anexample of a root logger section is given below.\begin{verbatim}[logger_root]level=NOTSEThandlers=hand01\end{verbatim}The \code{level} entry can be one of \code{DEBUG, INFO, WARNING,ERROR, CRITICAL} or \code{NOTSET}. For the root logger only,\code{NOTSET} means that all messages will be logged. Level values are\function{eval()}uated in the context of the \code{logging} package'snamespace.The \code{handlers} entry is a comma-separated list of handler names,which must appear in the \code{[handlers]} section. These names mustappear in the \code{[handlers]} section and have correspondingsections in the configuration file.For loggers other than the root logger, some additional information isrequired. This is illustrated by the following example.\begin{verbatim}[logger_parser]level=DEBUGhandlers=hand01propagate=1qualname=compiler.parser\end{verbatim}The \code{level} and \code{handlers} entries are interpreted as forthe root logger, except that if a non-root logger's level is specifiedas \code{NOTSET}, the system consults loggers higher up the hierarchyto determine the effective level of the logger. The \code{propagate}entry is set to 1 to indicate that messages must propagate to handlershigher up the logger hierarchy from this logger, or 0 to indicate thatmessages are \strong{not} propagated to handlers up the hierarchy. The\code{qualname} entry is the hierarchical channel name of the logger,that is to say the name used by the application to get the logger.Sections which specify handler configuration are exemplified by thefollowing.\begin{verbatim}[handler_hand01]class=StreamHandlerlevel=NOTSETformatter=form01args=(sys.stdout,)\end{verbatim}The \code{class} entry indicates the handler's class (as determined by\function{eval()} in the \code{logging} package's namespace). The\code{level} is interpreted as for loggers, and \code{NOTSET} is takento mean "log everything".The \code{formatter} entry indicates the key name of the formatter forthis handler. If blank, a default formatter(\code{logging._defaultFormatter}) is used. If a name is specified, itmust appear in the \code{[formatters]} section and have acorresponding section in the configuration file.The \code{args} entry, when \function{eval()}uated in the context ofthe \code{logging} package's namespace, is the list of arguments tothe constructor for the handler class. Refer to the constructors forthe relevant handlers, or to the examples below, to see how typicalentries are constructed.\begin{verbatim}[handler_hand02]class=FileHandlerlevel=DEBUGformatter=form02args=('python.log', 'w')[handler_hand03]class=handlers.SocketHandlerlevel=INFOformatter=form03args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)[handler_hand04]class=handlers.DatagramHandlerlevel=WARNformatter=form04args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)[handler_hand05]class=handlers.SysLogHandlerlevel=ERRORformatter=form05args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)[handler_hand06]class=NTEventLogHandlerlevel=CRITICALformatter=form06args=('Python Application', '', 'Application')[handler_hand07]class=SMTPHandlerlevel=WARNformatter=form07args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')[handler_hand08]class=MemoryHandlerlevel=NOTSETformatter=form08target=args=(10, ERROR)[handler_hand09]class=HTTPHandlerlevel=NOTSETformatter=form09args=('localhost:9022', '/log', 'GET')\end{verbatim}Sections which specify formatter configuration are typified by the following.\begin{verbatim}[formatter_form01]format=F1 %(asctime)s %(levelname)s %(message)sdatefmt=\end{verbatim}The \code{format} entry is the overall format string, and the\code{datefmt} entry is the \function{strftime()}-compatible date/time formatstring. If empty, the package substitutes ISO8601 format date/times, whichis almost equivalent to specifying the date format string "%Y-%m-%d %H:%M:%S".The ISO8601 format also specifies milliseconds, which are appended to theresult of using the above format string, with a comma separator. An exampletime in ISO8601 format is \code{2003-01-23 00:29:50,411}.\subsection{Using the logging package}\subsubsection{Simplest usage}Here's a simple example which shows the most casual usage of the loggingpackage.\begin{verbatim}import logginglogging.debug("Houston, we have a %s", "thorny problem")logging.info("Houston, we have a %s", "interesting problem")logging.warning("Houston, we have a %s", "bit of a problem")logging.error("Houston, we have a %s", "major problem")logging.critical("Houston, we have a %s", "major disaster")try:	infinity = 1 / 0except:	logging.exception("Houston, we have an %s", "unexpected problem")\end{verbatim}If you run the above example, this will produce:\begin{verbatim}WARNING:root:Houston, we have a bit of a problemERROR:root:Houston, we have a major problemCRITICAL:root:Houston, we have a major disasterERROR:root:Houston, we have an unexpected problemTraceback (most recent call last):  File "C:\Projects\RDC\Python\packages\logging\test\tmp.py", line 8, in ?    infinity = 1 / 0ZeroDivisionError: integer division or modulo by zero\end{verbatim}The reason you get this output is that the default format is\begin{verbatim}"%(levelname)s:%(name)s:%(message)s".\end{verbatim}When you invoke functions \function{info()}, \function{warning()} etc. in thelogging package itself, these calls are delegated to the correspondinglynamed methods in the root logger. This is why the logger name shown in the abovelogging output is "root". If the root logger has no handlers configured, thelogging package creates a console handler and adds it to the root loggerautomatically. (It does this by calling the \function{basicConfig()}, which youcan also call directly from your own code.)By default, events with a severity below WARNING are suppressed. Noticethat the \function{exception()} function acts like \function{error()}, exceptthat a traceback is appended to the log entry.\subsubsection{Logging to the console}Here's a simple example which logs all messages to the console. We use a namedlogger:\begin{verbatim}import logginglogging.basicConfig()logger = logging.getLogger('myapp')logger.setLevel(logging.DEBUG)logger.debug("Houston, we have a %s", "thorny problem")logger.info("Houston, we have a %s", "interesting problem")logger.warning("Houston, we have a %s", "bit of a problem")logger.error("Houston, we have a %s", "major problem")logger.critical("Houston, we have a %s", "major disaster")try:	infinity = 1 / 0except:	logger.exception("Houston, we have an %s", "unexpected problem")\end{verbatim}Here's the corresponding output:\begin{verbatim}DEBUG:myapp:Houston, we have a thorny problemINFO:myapp:Houston, we have a interesting problemWARNING:myapp:Houston, we have a bit of a problemERROR:myapp:Houston, we have a major problemCRITICAL:myapp:Houston, we have a major disasterERROR:myapp:Houston, we have an unexpected problemTraceback (most recent call last):  File "C:\Projects\RDC\Python\packages\logging\test\tmp.py", line 11, in ?    infinity = 1 / 0ZeroDivisionError: integer division or modulo by zero\end{verbatim}As you can see, the specified logger name now appears in the output, andDEBUG and INFO messages are included in the output because we explicitlyasked for them via the call to \method{setLevel()}.\subsubsection{Logging to a file}Here's a simple logging example that just logs to a file. In order,it creates a \class{Logger} instance, then a \class{FileHandler}and a \class{Formatter}. It attaches the \class{Formatter} to the\class{FileHandler}, then the \class{FileHandler} to the \class{Logger}.Finally, it sets a debug level for the logger.\begin{verbatim}import logginglogger = logging.getLogger('myapp')hdlr = logging.FileHandler('/var/tmp/myapp.log')formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')hdlr.setFormatter(formatter)logger.addHandler(hdlr)logger.setLevel(logging.WARNING)\end{verbatim}We can use this logger object now to write entries to the log file:\begin{verbatim}logger.error('We have a problem')logger.info('While this is just chatty')\end{verbatim}If we look in the file that was created, we'll see something like this:\begin{verbatim}2003-07-08 16:49:45,896 ERROR We have a problem\end{verbatim}The info message was not written to the file - we called the \method{setLevel}method to say we only wanted \code{WARNING} or worse, so the info message isdiscarded.The timestamp is of the form``year-month-day hour:minutes:seconds,milliseconds.''Note that despite the three digits of precision in the milliseconds field,not all systems provide time with this much precision.\subsubsection{Logging to a rotating set of files}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -