The log module in Python logging

Source: Internet
Author: User
Tags join root directory in python

This article mainly introduces the log module logging in Python, including the log level under Python and the use of commonly used methods in the module, friends can refer to the following

A log module is used in many applications to record key information during the operation of the system so that it can track the health of the system. In the. NET platform, there are very well-known Third-party open source log Components log4net,c++, there are familiar log4cpp, while in Python, we do not need third-party log components, because it has provided us with Easy-to-use, and powerful log 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 logs to a Web server as an HTTP GET or post, logging in the form of Windows events, and so on. These log saves can be used in combination, and each way you can set your 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 specific learning log processing.

First look at a relatively simple example, let us have a perceptual understanding of the logging module:

?

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

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

4 main components

Logger: Log class, where applications often log logs by invoking the APIs it provides;

Handler: Log information processing, you can send (save) the log to a different target domain;

Filter: Filtering the log information;

Formatter: The format of the log;

Log level

When logging is logged, the log message associates a level ("level" is essentially a non-negative integer). The system defaults to 6 levels, which are:

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

Common functions in the logging module:

Logging.basicconfig ([**kwargs]):

Configure basic information for the log module. Kwargs supports the following key parameters:

FileName: The save path for the log file. 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 ', then a new log file will be created each time the program starts;

Format: Sets the log output formats;

DATEFMT: define date format;

Levels: Sets the level of the log. Log messages below this level will be ignored;

Stream: sets a specific stream for initialization of Streamhandler;

The following is a simple example:

?

1 2 3 4 5 6 7 8 9 10 11 12 13-14 #coding =GBK Import Logging logging.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:error Logging.getlogger ([name])

Creates a logger object. The work of logging is done primarily by the Logger object. To provide the name of the logger when calling GetLogger (note: The GetLogger is invoked multiple times with the same name, and a reference to the same object is returned. , logger instances have hierarchical relationships that are represented by logger names, such as:

?

1 2 3 4 5 p = Logging.getlogger ("root") C1 = Logging.getlogger ("root.c1″) C2 = Logging.getlogger (" Root.c2″)

In the example, p is the parent logger, and the C1,C2 is the sub logger of P. C1, C2 will inherit P's settings. If the name parameter is omitted, GetLogger returns the root logger in the log object hierarchy.

Logging.setloggerclass (Klass)

Logging.getloggerclass ()

Gets/sets the journal type. Users can customize the log class to replace the logging provided by the system. Logger class.

Logging.getlevelname (LVL)

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

?

1 2 3 4 5 6 7 8 9 10 Print Logging.getlevelname (logging. NOTSET) #logging print logging.getlevelname. DEBUG print logging.getlevelname (logging. DEBUG) Print logging.getlevelname (#logging). WARN print logging.getlevelname (logging. ERROR) print logging.getlevelname (m) #logging. CRITICAL Logging.shutdown ()

When the log system is no longer used, the method is invoked, which flush the log to the corresponding target domain. Typically 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 demonstrates the Setlevel method:

?

1 2 3 4 5 6 7 8 9 10 #coding =GBK Import Logging logging.basicconfig (filename = Os.path.join (OS.GETCWD (), ' Log.txt '), level = logging. DEBUG) log = Logging.getlogger (' root.test ') log.setlevel (logging. WARN) #日志记录级别为WARNNING log.info (' info ') #不会被记录 log.debug (' Debug ') #不会被记录 log.warning (' warnning ') log.error (' ERROR ') Logger.debug (msg [, *args [, **kwargs]])

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

?

1 2 3 4 5 6 7 8 9 10 Import logging logging.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[, **kwarg S]] Logger.error (msg[, *args[, **kwargs]) logger.critical (msg[, *args[, **kwargs])

Log information for the appropriate level is logged. Parameters have the same meaning as logger.debug.

Logger.log (LVL, msg[, *args[, **kwargs])

Logging, parameter LVL users set the level of log information. Parameters 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 message. Logger.exception is used in exception-handling blocks, such as:

?

1 2 3 4 5 6 7 8 Import logging logging.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 ') #异常信 is automatically added to the log message

Logger.addfilter (filt)

Logger.removefilter (filt)

Adds/removes log message filters. Describe the filter in detail.

Logger.addhandler (HDLR)

Logger.removehandler (HDLR)

Adds/Removes the log message processor. Describe handler in detail.

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.

Related Article

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.