Python logging and pythonlogging

Source: Internet
Author: User

Python logging and pythonlogging
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

Parameters of the logging. basicConfig function:
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'): root: INFO This is info messageroot: 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
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: the log is output to the stream, which can be sys. stderr, sys. stdout or file logging. fileHandler: the log is output to the file log rollback mode. In actual use, RotatingFileHandler and TimedRotatingFileHandlerlogging are used. handlers. baseRotatingHandlerlogging. handlers. rotatingFileHandlerlogging. handlers. timedRotatingFileHandlerlogging. handlers. socketHandler: remotely outputs logs to TCP/IP socketslogging. handlers. datagramHandler: remotely outputs logs to UDP socketslogging. handlers. SMTPHandler: remotely outputs logs to the mail address logging. handlers. sysLogHandler: logs are output to syslogging. handlers. NTEventLogHandler: remote log output to Windows NT/2000/XP Event Log logging. handlers. memoryHandler: Specifies bufferlogging when logs are output to memory. 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 python2.5 manual.

#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=

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

 

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.