Use python's logging module and pythonlogging Module

Source: Internet
Author: User

Use python's logging module and pythonlogging Module

I. Starting from a use case

 

To develop a log system, you must output logs to the console and write 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 for writing log files
  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 handler output format
  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 the console and the log file:

 

Java code
  1. 19:18:29, 816-mylogger-INFO-foorbar

 

 

Ii. APIs of the logging Module

 

Based on the example above, let's talk about several of the most commonly used APIs.

Logging.GetLogger([Name])Returns a logger instance. If no name is specified, the root logger is returned. As long as the names are the same, the returned logger instances are the same and only one, that is, the names and logger instances correspond one to one. This means that you do not need to pass the logger instance in each module. You only need to know the name to get the same logger instance.
Logger.SetLevel(Lvl)Set the logger level. The level has the following levels:

NOTSET <DEBUG <INFO <WARNING <ERROR <CRITICAL
If the looger level is set to INFO, no logs smaller than INFO level are output, and logs larger than or equal to INFO level are output.

Python code
  1. Logger. debug ("foobar") # No output
  2. Logger.info ("foobar") # output
  3. Logger. warning ("foobar") # output
  4. Logger. error ("foobar") # output
  5. Logger. critical ("foobar") # output

 Logger.AddHandler(Hdlr)Logger can employ handler to process logs. handler mainly has the following types:StreamHandler: output to the consoleFileHandler: output to fileHandler can also set its own level and output format.
Logging.BasicConfig([** Kwargs])* This function is used to configure the root logger, create a StreamHandler for the root logger, and set the default format. * These functions: logging. debug (), logging.info (), and logging. warning (), logging. error (), logging. critical () if the root logger does not have any handler when it is called, it will automatically call basicConfig to add a handler * If the root logger already has a handler, this function will 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 ('this message shoshould appear on the console ')

 
Iii. relationship between root logger and logger
As mentioned previously, the root logger instance has a parent-child relationship. The root logger is the top-level logger, which is the ancestor of all logger. For example:Root logger is the default logger.If you do not create a logger instance, you can directly call logging. debug (), logging.info () logging. warning (), logging. error (), logging. critical () functions, the logger used is the root logger, which can be automatically created and is also a single instance.
How to obtain the root loggerUse logging. getLogger () or logging. getLogger ("") to obtain the root logger instance.
Default levelThe default level of root logger is logging. WARNING.
How to represent a parent-child relationshipThe name of a logger can indicate the parent-child relationship between logger. For example, parent_logger = logging. getLogger ('foo') child_logger = logging. getLogger ('foo. bar ')
What is dynamic level?Logger has a concept called valid level. If a logger does not explicitly set the level, it uses the level of the father. If the father does not explicitly set the level, he will use his father's level to push... and finally reach the root logger. The level must have been set. The default value is logging. WARNINGchild. After obtaining a message, the loggers distribute the message to the handler and send it to all the previous logger for processing,
Let's 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 the 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. 21:04:29, 893-foo
  2. 21:04:29, 893-DEBUG-foo


It can be seen that the child logger does not have any handler, so the message is not processed. However, it forwards the message to its father and root logger. Finally, two logs are output.


Where is the default log file stored in the logging module of python?

When configuring log file objects, you need to fill in the location of the log file. I put them all according to project requirements.
No research is performed by default.

Does python logging not output to the screen?

So where do you want to output it? You can intercept sys. stdout.

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.