Introduction to the logging module of python

Source: Internet
Author: User

Introduction to the logging module of python

Recently, I was writing a program that uses python to generate an App. I found that printing information directly with print is not convenient and standardized. Therefore, I used the logging Log Module to simply record the usage. I should use logging in a formal project. config configuration logs can be used to limit the size, format control, and output location of log files similar to log4j.

1. Simply print logs to the screen
import logginglogging.debug('This is debug message')logging.info('This is info message')logging.warning('This is warning message')
WARNING: root: This is warning message


By default, logging prints logs to the screen at the Log Level of WARNING;
The log level relationship is: CRITICAL> ERROR> WARNING> INFO> DEBUG> NOTSET. You can also define the log level by yourself.

2. Use the logging. basicConfig function to configure the log output format and method.
Import logginglogging. basicConfig (level = logging. DEBUG, format = '% (asctime) s % (filename) s [line: % (lineno) d] % (levelname) s % (message) s ', datefmt = '% a, % d % B % Y % H: % M: % s', filename = 'myapp. log', filemode = 'W') logging. debug ('this is debug message') logging.info ('this is info message') logging. warning ('this is warning message '). /myapp. the log file contains the following content: Sun, 24 May 2009 21:48:54 demo2.py [line: 11] DEBUG This is debug messageSun, 24 May 2009 21:48:54 demo2.py [line: 12] INFO This is info messageSun, 24 May 2009 21:48:54 demo2.py [line: 13] WARNING This is warning message



Filename: Specifies the log file name.
Filemode: Same as the file function. It specifies the log file opening mode, 'w' or 'A'
Format: Specify the output format and content. format can output a lot of useful information, as shown in the preceding example:
% (Levelno) s: print the log-level value
% (Levelname) s: print the Log Level name
% (Pathname) s: print the path of the current execution program, which is actually sys. argv [0]
% (Filename) s: print the name of the currently executed Program
% (FuncName) s: current function for printing logs
% (Lineno) d: print the current line number of the log
% (Asctime) s: log printing time
% (Thread) d: Print thread ID
% (ThreadName) s: print the thread name
% (Process) d: print the process ID
% (Message) s: Print log information
Datefmt: specifies the time format, which is the same as time. strftime ()
Level: Set the log level. The default value is logging. WARNING.
Stream: Specifies the output stream of logs. You can specify the output stream to sys. stderr, sys. stdout or file, which is output to sys by default. stderr. When stream and filename are both specified, stream is ignored.

3. Output logs to both files and screens.
Import logginglogging. basicConfig (level = logging. DEBUG, format = '% (asctime) s % (filename) s [line: % (lineno) d] % (levelname) s % (message) s ', datefmt = '% a, % d % B % Y % H: % M: % s', filename = 'myapp. log', filemode = 'W ') ######################################## ######################################## ################# define a StreamHandler, print the INFO-level or higher log information to a standard error and add it to the current log processing object # console = logging. streamHandler () console. setLevel (logging. INFO) formatter = logging. formatter ('% (name)-12 s: % (levelname)-8 s % (message) s') console. setFormatter (formatter) logging. getLogger (''). addHandler (console) ######################################## ######################################## ################# logging. debug ('this is debug message') logging.info ('this is info message') logging. warning ('this is warning message ')

Screen Printing:
Root : INFO This is info message
Root : WARNINGThis is warning message

The./myapp. log file contains the following content:
Sun, 24 May 2009 21:48:54 demo2.py [line: 11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py [line: 12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py [line: 13] WARNING This is warning message



4. Log rollback with logging
Import loggingfrom logging. handlers import RotatingFileHandler ##################################### ######################################## #################### define a RotatingFileHandler, up to five log files can be backed up, with each log file up to 10 MRthandler = RotatingFileHandler ('myapp. log', maxBytes = 10*1024*1024, backupCount = 5) Rthandler. setLevel (logging. INFO) formatter = logging. formatter ('% (name)-12 s: % (levelname)-8 s % (message) s') Rthandler. setFormatter (formatter) logging. getLogger (''). addHandler (Rthandler) ######################################## ######################################## ################

From the above example, we can see that logging has a main log processing object. Other processing methods are added through addHandler.

Several handle methods of logging are as follows:

Logging. StreamHandler: logs are output to the stream, which can be sys. stderr, sys. stdout, or files.
Logging. FileHandler: logs are output to files.

Log rollback method. RotatingFileHandler and TimedRotatingFileHandler are used in actual use.
Logging. handlers. BaseRotatingHandler
Logging. handlers. RotatingFileHandler
Logging. handlers. TimedRotatingFileHandler

Logging. handlers. SocketHandler: remotely outputs logs to TCP/IP sockets
Logging. handlers. DatagramHandler:Remotely output logs to UDP sockets
Logging. handlers. SMTPHandler:Remotely output logs to the email address
Logging. handlers. SysLogHandler: syslog output
Logging. handlers. NTEventLogHandler: remotely outputs Event Logs to Windows NT/2000/XP.
Logging. handlers. MemoryHandler: the buffer used to output logs to the memory.
Logging. handlers. HTTPHandler: Remote output to the HTTP server through "GET" or "POST"

Because StreamHandler and FileHandler are common log processing methods, they are directly included in the logging module, while other methods are included in the logging. handlers module,
For more information about how to use the above processing methods, see the python2.5 manual!


5. Configure logs through the logging. config module
#logger.conf###############################################[loggers]keys=root,example01,example02[logger_root]level=DEBUGhandlers=hand01,hand02[logger_example01]handlers=hand01,hand02qualname=example01propagate=0[logger_example02]handlers=hand01,hand03qualname=example02propagate=0###############################################[handlers]keys=hand01,hand02,hand03[handler_hand01]class=StreamHandlerlevel=INFOformatter=form02args=(sys.stderr,)[handler_hand02]class=FileHandlerlevel=DEBUGformatter=form01args=('myapp.log', 'a')[handler_hand03]class=handlers.RotatingFileHandlerlevel=INFOformatter=form02args=('myapp.log', 'a', 10*1024*1024, 5)###############################################[formatters]keys=form01,form02[formatter_form01]format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)sdatefmt=%a, %d %b %Y %H:%M:%S[formatter_form02]format=%(name)-12s: %(levelname)-8s %(message)sdatefmt=

The preceding configuration file shows the inclusion relationships of formatter, handler, and loggers. After carefully studying this configuration file, you will understand it!

Example 3:

import loggingimport logging.configlogging.config.fileConfig("logger.conf")logger = logging.getLogger("example01")logger.debug('This is debug message')logger.info('This is info message')logger.warning('This is warning message')

Example 4:

import loggingimport logging.configlogging.config.fileConfig("logger.conf")logger = logging.getLogger("example02")logger.debug('This is debug message')logger.info('This is info message')logger.warning('This is warning message')


6. Note that logging is thread-safe.


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.