Description of the Python log logging module

Source: Internet
Author: User

Recently, in writing a program that uses Python to generate apps, it is found that printing information directly with print is less convenient and prescriptive, so using the logging log module, simply record the usage, The Logging.config configuration log should be used in a formal project to achieve log file size limits like log4j, format control, output location, and so on.

1. Simply print the log to the screen
Import Logginglogging.debug (' This was debug message ') Logging.info (' This is Info message ') logging.warning (' This is Warning message ')
WARNING:root:This is WARNING message


By default, logging prints the log to the screen with a log level of warning;
Log level size relationships are: CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET, and of course you can define the log level yourself.

2. Configure the output format and mode of the log by Logging.basicconfig function
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 the Debug message ') Logging.info (' This  is Info message ') logging.warning (' This is warning message '). The contents of the/myapp.log file are: Sun, May 21:48:54 Demo2.py[line:11]  Debug this was debug Messagesun, 21:48:54 Demo2.py[line:12] Info This is info Messagesun, 2009 21:48:54 DEMO2.PY[LINE:13] WARNING This is WARNING message



FileName: Specify the log file name
FileMode: Same as file function, specify open mode of log file, ' W ' or ' a '
Format: Specifies the formats and contents of the output, format can output a lot of useful information, as in the example above:
% (Levelno) S: Print the value of the log level
% (levelname) S: Print log level name
% (pathname) s: Prints the path of the currently executing program, which is actually sys.argv[0]
% (filename) s: Prints the current name of the executing program
% (funcName) s: Print the current function of the log
% (Lineno) d: Print the current line number of the log
% (asctime) s: Time to print logs
% (thread) d: Print thread ID
% (threadname) s: Print thread name
% (process) d: Print process ID
% (message) s: Print log information
DATEFMT: Specify time format, same as Time.strftime ()
Level: Sets the log levels by default to logging. WARNING
Stream: Specifies the output stream that will log, can specify output to Sys.stderr,sys.stdout or file, default output to Sys.stderr, stream is ignored when stream and filename are specified simultaneously

3. Output logs to both file and screen at the same time
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 ',                

on-screen printing:
Root: INFOThis is info message
Root: WARNINGThis is warning message

./myapp.log文件中内容为:
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.logging Log Rollback
Import loggingfrom logging.handlers Import rotatingfilehandler#################################################### ############################################# #定义一个RotatingFileHandler, backup up to 5 log files, maximum 10MRthandler per log file Rotatingfilehandler (' Myapp.log ', maxbytes=10*1024*1024,backupcount=5) rthandler.setlevel (logging.info) formatter = Logging. Formatter ('% (name) -12s:% (levelname) -8s% (message) s ') Rthandler.setformatter (Formatter) Logging.getlogger ('). AddHandler (Rthandler) ######################################################################################### #######

As can be seen from the above example and in this example, logging has a main object of log processing, and other processing methods are added through AddHandler.

Several handle methods of logging are as follows:

Logging. Streamhandler: Log output to stream, can be sys.stderr, sys.stdout, or file
Logging. Filehandler: Log output to File

Log rollback method, use Rotatingfilehandler and Timedrotatingfilehandler in practice
logging.handlers.baserotatinghandler< BR style= "margin:0px; padding:0px ">logging.handlers.rotatingfilehandler
LOGGING.HANDLERS.TIMEDROTATINGFILEHANDLER

logging.handlers.sockethandler: Remote output log to TCP/IP sockets
LOGGING.HANDLERS.DATAGRAMHANDLER:&NBSP;  remote output log to UDP sockets
logging.handlers.smtphandler:   remote output log to e-mail address
logging.handlers.sysloghandler: Log output to SYSLOG
Logging.handlers.NTEventLogHandler: Remote output log to Windows NT/2000/XP event log
Logging.handlers.MemoryHandler: Log output to in-memory development buffer

Because Streamhandler and filehandler are common log processing methods, they are included directly in the logging module, while others are included in the Logging.handlers module.
Please refer to the python2.5 manual for the use of the other processing methods described above.


5. Configuring logs via 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=

From the above configuration file can be seen formatter, handler, loggers the inclusion of the relationship, carefully study this configuration file will understand!

In 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 ')

in 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. Finally 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.