Detailed description of the log module in Python logging

Source: Internet
Author: User
In many applications, a log module is used to record key information about the system's operation, so that it can track the health of the system. In the. NET platform, there are well-known third-party open-source log components log4net,c++, with familiar log4cpp, and in Python we don't need a third-party log component because it has provided us with an easy-to-use and powerful logging module: logging. The logging module supports saving log information to a different target domain, such as saving to a log file, sending log information as a message, submitting a log to a Web server as an HTTP GET or post, logging as a Windows event, and so on. These log save methods can be used in combination, each of which can set its own log level and log format. The content of the log module is more, today first learn the basic use of logging module, the next time the specific study log processing.

Let's look at a relatively simple example, so that we have a perceptual understanding of the logging module:

Import logginglogging.basicconfig (filename = Os.path.join (OS.GETCWD (), ' Log.txt '), level = logging. DEBUG) Logging.debug (' This is a message ')

The code that runs the example above will create a Log.txt file in the root directory of the program, open the file with a log record: "DEBUG:root:this is a message".
4 main components

    1. Logger: The log class, which the application often logs by invoking the API it provides;
    2. Handler: The Log information processing, the log can be sent (saved) to a different target domain;
    3. Filter: Filtering the log information;
    4. Formatter: The format of the log;

Log level

When logging is logged, the log message is associated with a level ("level" is essentially a non-negative integer). The system provides 6 levels by default, each of which is:

You can set the log level to a Log object (Logger Instance), log messages below that level will be ignored, or you can set the log level to Hanlder, and handler are ignored for log messages below that level.

Common functions in the logging module:
Logging.basicconfig ([**kwargs]):

Configure basic information for the log module. Kwargs supports several keyword parameters:

    • FileName: The path where the log file is saved. If some parameters are configured, a Filehandler is automatically created as a handler;
    • FileMode: The open mode of the log file. The default value is ' a ', which means that the log message is added to the log file as an append. If set to ' W ', a new log file will be created each time the program starts;
    • Format: Set the log output formats;
    • DATEFMT: Define the date format;
    • Levels: Sets the level of the log. Log messages below this level will be ignored;
    • Stream: Sets the specific stream used to initialize the Streamhandler;

The following is a simple example:

#coding =gbkimport logginglogging.basicconfig (filename = Os.path.join (OS.GETCWD (), ' Log.txt '),/level  = logging. WARN, FileMode = ' W ', format = '% (asctime) s-% (levelname) s:% (message) s ') logging.debug (' Debug ') #被忽略logging. info (' info ') )  #被忽略logging. Warning (' warn ') logging.error (' ERROR ') #-----Results #2009-07-13 21:42:15,592-WARNING:WARN#2009-07-13 21:42:15,640-error:errorlogging.getlogger ([name])

Creates a logger object. The work of logging is mainly done by the logger object. Provide the name of the logger when calling GetLogger (note: The same name is used more than once to invoke GetLogger, which returns a reference to the same object.) ), logger instances have hierarchical relationships, which are represented by logger names, such as:

p = Logging.getlogger ("root") C1 = Logging.getlogger ("Root.c1″") C2 = Logging.getlogger ("Root.c2″")

In the example, p is the parent logger, and C1,C2 is the child logger of P respectively. C1, C2 will inherit the settings of P. If the name parameter is omitted, GetLogger returns the root logger in the log object hierarchy.
Logging.setloggerclass (Klass)
Logging.getloggerclass ()

Gets/sets the log type. Users can customize the log class to replace the system-provided logging. Logger class.
Logging.getlevelname (LVL)

Gets the name corresponding to the log level. For example:

Print Logging.getlevelname (logging. NOTSET) Print Logging.getlevelname (Ten) #logging. DebugPrint Logging.getlevelname (logging. DEBUG) Print logging.getlevelname (#logging). Warnprint Logging.getlevelname (logging. ERROR) Print logging.getlevelname (#logging). Criticallogging.shutdown ()

When the log system is no longer used, the method is called, which flush the log to the corresponding target domain. This is usually called when the system exits.

The Logger object is created by calling Logging.getlogger (name), which has the following common methods and properties:
Logger.setlevel (LVL):

Sets the level of the log. Log messages that are below this level are ignored. The following example shows the Setlevel method:

#coding =gbkimport logginglogging.basicconfig (filename = Os.path.join (OS.GETCWD (), ' Log.txt '), level = logging. DEBUG) log = Logging.getlogger (' root.test ') log.setlevel (logging. WARN) #日志记录级别为WARNNINGlog. info (' info ')  #不会被记录log. Debug (' Debug ') #不会被记录log. Warning (' warnning ') log.error (' Error ') Logger.debug (msg [, *args [, **kwargs]])

Log information at the debug level is logged. The parameter msg is the format of the information, and the args and Kwargs are format parameters respectively.

Import logginglogging.basicconfig (filename = Os.path.join (OS.GETCWD (), ' Log.txt '), level = logging. DEBUG) log = Logging.getlogger (' root ') log.debug ('%s,%s,%s ', * (' Error ', ' Debug ', ' Info ') log.debug ('% (module) s,% (info  S ', {' module ': ' Log ', ' Info ': ' ERROR '}) Logger.info (msg[, *args[, **kwargs]) logger.warnning (msg[, *args[, **kwargs] ]) Logger.error (msg[, *args[, **kwargs]) logger.critical (msg[, *args[, **kwargs])

Log information at the appropriate level is logged. The meaning of the parameter is the same as Logger.debug.
Logger.log (LVL, msg[, *args[, **kwargs])

Logging, parameter LVL user sets the level of log information. Parameter msg, *args, **kwargs the same meaning as logger.debug.
Logger.exception (msg[, *args])

Log messages are logged at the error level, and exception tracking information is automatically added to the log messages. Logger.exception is used in exception handling blocks, such as:

Import logginglogging.basicconfig (filename = Os.path.join (OS.GETCWD (), ' Log.txt '), level = logging. DEBUG) log = Logging.getlogger (' root ') Try:  raise Exception, ' This is a Exception ' except:  log.exception (' Exception ') #异常信息被自动添加到日志消息中
Logger.addfilter (filt)
Logger.removefilter (filt)

Add/Remove log message filter. Specifically described when you tell the filter.
Logger.addhandler (HDLR)
Logger.removehandler (HDLR)

Add/Remove log message processors. Described in detail when handler.
Logger.makerecord (name, LVL, FN, Lno, msg, args, exc_info[, Func, Extra])

Creates a LogRecord object. The log message is instantiated as a LogRecord object and processed within the log class.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.