[Blog recommendation] logging module of python Howto (1)

Source: Internet
Author: User

[Blog recommendation] logging module of python Howto (1)

This blog post is from Bkjia. If you have any questions, go to the blog page for an interactive discussion!
Blog: http://xdzw608.blog.51cto.com/4812210/1608718

This article comes from the understanding of the source code added to the howto-logging section in py2.7.9 docs. The official documentation link is as follows, I am using the downloaded pdf version, should be consistent: https://docs.python.org/2/howto/logging.html

We do not follow the order described in the document, because there is no "in" for such a thing.

Using the logging module to record logs involves four main categories. It is most appropriate to use the general description in the official documentation:

Logger provides interfaces that can be directly used by applications;

Handler sends the (logger created) log records to the appropriate destination output;

Filter provides a device with fineness to determine which log records to output;

Formatter determines the final output format of the log record.

The general order of log writing is:

1. Create a logger:

Instead of directly instantiating Logger through logging. logger, We need to generate a logger object through logging. getLogger ("name.

It does not mean that we cannot instantiate Logger, but we expect the same logger from the same name, so that multiple modules can use the same logger together, getLogger is a solution that is internally maintained using the loggerDict dictionary. It ensures that the same logger object is obtained by using the same name as the key. We can verify it through an instance:

 
 
  1. # Test_logger1.py
  2.  
  3. # Coding: UTF-8
  4.  
  5. Import logging
  6.  
  7. Print logging. getLogger ("mydear ")
  8.  
  9. Import test_logger2
  10.  
  11. Test_logger2.run () # Call the function in file 2 to ensure that both modules are active together
  12.  
  13. # Test_logger2.py
  14.  
  15. # Coding: UTF-8
  16. Import logging
  17.  
  18. Def run ():
  19.  
  20. Print logging. getLogger ("mydear ")

Output:

<Logging. Logger object at 0x00000000020ECF28>
<Logging. Logger object at 0x00000000020ECF28>

The results show that calling getLogger through "mydear" in the two files ensures that the obtained logger object is the same. However, the instantiation of the Logger classes is not guaranteed.

With logger, you can configure this logger, such as setting the Log Level setLevel, binding the Controller addHandler, and adding the filter addFilter.

After the configuration is complete, you can call the logger method to write logs. Five log-level pairs should have five log-record Methods: logger. debug, logger.info, logger. warning, logger. error, logger. critical.

2. Configure the Log Level of the Logger object:

Logger. setLevel (logging. DEBUG) # The log level above DEBUG will be processed by this logger

3. Create a handler object

Handler is responsible for distributing logs to a specific destination output. There are multiple built-in Handler that distribute logs to different destinations, or the console, or files, or some form of stream, or socket. A logger can bind multiple handler. For example, a log can be output to the console and file at the same time.

Taking FileHandler and StreamHandler as examples:

Logfile = logging. FileHandler ("./log.txt") # create a handler to output logs to files.

Console = logging. StreamHandler () # create another handler and direct logs to the stream

You also need to set the log level for the handler object. Because a logger can contain multiple handler, it is necessary to set the log level for each handler. In plain words, for example, we need to process messages at or above the debug level, so we set the Log Level of logger to DEBUG; then we want to output logs above the error to the console, the messages above DEBUG are output to the file, which requires two Handler to control the shunting.

Logfile. setLevel (logging. DEBUG)

Console. setLevel (logging. ERROR)

Besides setting the log level for the handler object, you can also specify the formatter, that is, the log output format. Setting the log format for the handler object indicates that a record can be output to the console, file, or other destinations in different formats.

Formatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ')

Logfile. setFormatter (formatter) # Set the log output format of handler

Keywords used when formatter is created are displayed in the form of a list. This is not the focus.

4. Bind handler to logger

Now that handlers and logger are ready, we will bind handlers to logger. a logger object can bind multiple handler.

Logger. addHandler (logfile) # logger is the Logger object obtained by getLogger.

Logger. addHandler (console)

5. Use logger to truly write logs

Logger. debug ("some debug message .")

Logger.info ("some info message .")

It seems that the intermediate steps (creating handler, setting the Log Level, and setting the output format) are more like configuring Logger. Once the configuration is complete, you can directly call the log writing interface, later, these logs will be output according to the previous configuration.

A lot of content. A little simple.

The following code is the simplest. Log writing is performed after logging is imported:

 
 
  1. #coding:utf-8 
  2. import logging 
  3.  
  4. logging.debug("debug mes") 
  5.  
  6. logging.info("info mes") 
  7.  
  8. logging.warning("warn mes") 

The console output is as follows:

WARNING: root: warn mes

Why? What happened? Why only warning is output? Where have handler, logger, and formatter been?

-_-! What is the easiest way to say yes? In order to give credit to myself, I try to interpret it as "the simplest ".


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.