Python Log Module --- logging, python --- logging

Source: Internet
Author: User

Python Log Module --- logging, python --- logging
1. Print logs to the screen

1 import logging2 3 logging.debug('This is debug message---by liu-ke')4 logging.info('This is info message---by liu-ke')5 logging.warning('This is warning message---by liu-ke')

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 define the log level by yourself.

 

2. Use the logging. basicConfig function to configure the log output format and method.
 1 import logging 2  3 logging.basicConfig(level=logging.DEBUG, 4                 format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', 5                 datefmt='%a, %d %b %Y %H:%M:%S', 6                 filename='mypy.log', 7                 filemode='w') 8      9 logging.debug('This is debug message by liu-ke')10 logging.info('This is info message by liu-ke')11 logging.warning('This is warning message by liu-ke')
1 logging. parameters of the basicConfig function: 2 filename: Specify the log file name 3 filemode: The same as the file function. Specify the log file opening mode, 'w' or 'A' 4 format: specify the output format and content. format can output a lot of useful information, as shown in the preceding example: 5% (levelno) s: print the log-level value 6% (levelname) s: print Log Level name 7% (pathname) s: print the path of the current execution program, which is actually sys. argv [0] 8% (filename) s: print the current execution program name 9% (funcName) s: print the log of the current function 10% (lineno) d: the current row number of the print log 11% (asctime) s: the time when the log is printed 12% (thread) d: Print thread ID13 % (threadName) s: Print thread name 14% (process) d: print process ID15 % (message) s: Print log information 16 datefmt: specifies the time format, the same as time. strftime () 17 level: Set the log level. The default value is logging. WARNING18 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.
1 import logging 2 3 logging. basicConfig (level = logging. DEBUG, 4 format = '% (asctime) s % (filename) s [line: % (lineno) d] % (levelname) s % (message) s ', 5 datefmt = '% a, % d % B % Y % H: % M: % s', 6 filename = 'mypy. log', 7 filemode = 'W ') 8 9 ###################################### ######################################## ################## 10 # define a StreamHandler, print INFO-level or higher log information to a standard error and add it to the current log processing object #11 console = logging. streamHandler () 12 console. setLevel (logging. INFO) 13 formatter = logging. formatter ('% (name)-12 s: % (levelname)-8 s % (message) s') 14 console. setFormatter (formatter) 15 logging. getLogger (''). addHandler (console) 16 ####################################### ######################################## ################# 17 18 logging. debug ('this is debug message') 19 logging.info ('this is info message') 20 logging. warning ('this is warning message ')

 

4. Log rollback with logging
1 import logging 2 from logging. handlers import RotatingFileHandler 3 4 ################################### ######################################## ###################### 5 # define a RotatingFileHandler, up to five log files can be backed up, with each log file up to 10 MB (custom) 6 Rthandler = RotatingFileHandler ('myapp. log', maxBytes = 10*1024*1024, backupCount = 5) 7 Rthandler. setLevel (logging. INFO) 8 formatter = logging. formatter ('% (name)-12 s: % (levelname)-8 s % (message) s') 9 Rthandler. setFormatter (formatter) 10 logging. getLogger (''). addHandler (Rthandler) 11 ####################################### ######################################## ############

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:

1 logging. streamHandler: the log is output to the stream, which can be sys. stderr, sys. stdout or file 2 logging. fileHandler: log output to file 3 log rollback mode. In actual use, use RotatingFileHandler and TimedRotatingFileHandler 4 logging. handlers. baseRotatingHandler 5 logging. handlers. rotatingFileHandler 6 logging. handlers. timedRotatingFileHandler 7 logging. handlers. socketHandler: remotely outputs logs to TCP/IP sockets 8 logging. handlers. datagramHandler: remotely outputs logs to UDP sockets 9 logging. handlers. SMTPHandler: remotely outputs logs to the mail address 10 logging. handlers. sysLogHandler: logs are output to syslog11 logging. handlers. NTEventLogHandler: remote log output to Windows NT/2000/XP Event Log 12 logging. handlers. memoryHandler: Specify buffer13 logging 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 the python2.7 manual!

 

5. Configure logs through the logging. config module
 1 #logger.conf 2 ############################################### 3 [loggers] 4 keys=root,example01,example02 5 [logger_root] 6 level=DEBUG 7 handlers=hand01,hand02 8 [logger_example01] 9 handlers=hand01,hand0210 qualname=example0111 propagate=012 [logger_example02]13 handlers=hand01,hand0314 qualname=example0215 propagate=016 ###############################################17 [handlers]18 keys=hand01,hand02,hand0319 [handler_hand01]20 class=StreamHandler21 level=INFO22 formatter=form0223 args=(sys.stderr,)24 [handler_hand02]25 class=FileHandler26 level=DEBUG27 formatter=form0128 args=('myapp.log', 'a')29 [handler_hand03]30 class=handlers.RotatingFileHandler31 level=INFO32 formatter=form0233 args=('myapp.log', 'a', 10*1024*1024, 5)34 ###############################################35 [formatters]36 keys=form01,form0237 [formatter_form01]38 format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s39 datefmt=%a, %d %b %Y %H:%M:%S40 [formatter_form02]41 format=%(name)-12s: %(levelname)-8s %(message)s42 datefmt=

Example 3:

1 import logging2 import logging.config3 4 logging.config.fileConfig("logger.conf")5 logger = logging.getLogger("example01")6 7 logger.debug('This is debug message')8 logger.info('This is info message')9 logger.warning('This is warning message')

Example 4:

1 import logging2 import logging.config3 4 logging.config.fileConfig("logger.conf")5 logger = logging.getLogger("example02")6 7 logger.debug('This is debug message')8 logger.info('This is info message')9 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.