Using Python's logging module

Source: Internet
Author: User

First, starting from a usage scenario

Develop a log system that outputs logs to the console and to log files

Python code
  1. Import logging
  2. # Create a Logger
  3. Logger = Logging.getlogger (' MyLogger ')
  4. Logger.setlevel (logging. DEBUG)
  5. # Create a handler to write to the log file
  6. FH = logging. Filehandler (' Test.log ')
  7. Fh.setlevel (logging. DEBUG)
  8. # Create another handler for output to the console
  9. ch = logging. Streamhandler ()
  10. Ch.setlevel (logging. DEBUG)
  11. # define the output format of the handler
  12. Formatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ')
  13. Fh.setformatter (Formatter)
  14. Ch.setformatter (Formatter)
  15. # Add Handler to Logger
  16. Logger.addhandler (FH)
  17. Logger.addhandler (CH)
  18. # Record a log
  19. Logger.info (' Foorbar ')

After running, there is a log in both the console and the log file:

Java code
    1. 2011-08-: 816-mylogger-info-foorbar

Second, the Logging module API

In combination with the above example, we'll say a few of the most commonly used APIs

logging. GetLogger ([name]) Returns a logger instance that returns root logger if no name is specified. As long as name is the same, the returned logger instances are the same and only one, that is, the name and the logger instance are one by one corresponding. This means that there is no need to pass logger instances in each module. As long as you know name, you can get the same logger instance
Logger. SetLevel (lvl) sets the level of logger, which has the following levels:

NOTSET < DEBUG < INFO < WARNING < ERROR < CRITICAL
If the Looger level is set to info, then logs less than the info level are not output, and logs that are greater than or equal to the info level are output

Python code
    1. logger.debug (#  not output    
    2. logger.info (#  output   
    3. Logger.warning ( "Foobar")  #  output   
    4. logger.error ( "Foobar")        #  output   
    5. logger.critical (#  output   

Logger. AddHandler (hdlr)logger can hire handler to help it with the log, handler mainly have the following:streamhandler: Output to console Filehandler: Output to file handler can also set its own level and output format.
logging. Basicconfig ([**kwargs])* This function is used to configure root logger as root Logger Create a Streamhandler, set the default format. * These functions: Logging.debug (), Logging.info (), logging.warning (), Logging.error (), logging.critical () If the call finds root Logger does not have any handler, will automatically call Basicconfig add a handler* if root logger already has handler, this function does not do anything
Use Basicconfig to configure the output format and level of the root logger:

Python code
    1. import logging  
    2. Logging.basicconfig (Format= '% (levelname) s:% (message) s ',  level=logging. DEBUG)   
    3. logging.debug (


Third, about root logger and logger father-son relationship
The previous mentions of root logger, in fact logger instances there is a parent-child relationship, root logger is the topmost logger, it is all logger ancestors. such as:root logger is the default logger if you do not create logger instances, call Logging.debug (), Logging.info () logging.warning (), Logging.error (), logging.critical () These functions, the logger used is root logger, which can be created automatically and is a single instance.
how to get root logger by Logging.getlogger () or Logging.getlogger ("") to get the root logger instance.
The defaultlevel root logger default level is logging. WARNING
how to represent the name of a parent-child relationship logger can represent a parent-child relationship between logger. For example: Parent_logger = Logging.getlogger (' foo ') Child_logger = Logging.getlogger (' Foo.bar ')
what is effectivelevel logger has a concept called effective level. If a logger does not display the level, then it uses the level of the father. If the father does not display the level, just use the father's level to push .... At the end of the root logger, you must set the level. The default is logging. Warningchild Loggers received the message, both the message is distributed to its handler processing, also passed to all ancestors logger processing,
Take a look at an example

Python code
  1. Import logging
  2. # Set Root Logger
  3. R = Logging.getlogger ()
  4. ch = logging. Streamhandler ()
  5. Ch.setlevel (logging. DEBUG)
  6. Formatter = logging. Formatter ('% (asctime) s-% (levelname) s-% (message) s ')
  7. Ch.setformatter (Formatter)
  8. R.addhandler (CH)
  9. # Create a logger as a father
  10. p = logging.getlogger (' foo ')
  11. P.setlevel (logging. DEBUG)
  12. ch = logging. Streamhandler ()
  13. Ch.setlevel (logging. DEBUG)
  14. Formatter = logging. Formatter ('% (asctime) s-% (message) s ')
  15. Ch.setformatter (Formatter)
  16. P.addhandler (CH)
  17. # Create a child logger
  18. c = Logging.getlogger (' foo.bar ')
  19. C.debug (' foo ')

The output is as follows:

Python code
    1. 2011-08- :893-foo
    2. 2011-08- :893-debug-foo


As can be seen, the child logger without any handler, so the message is not processed. But it forwarded the message to its father and root logger. Output two logs at the end of the line.

Using Python's logging module

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.