This is the seventh day of my participation in the August More text Challenge. For details, see:August is more challenging

directory

  • 🔞 0. Preface:
  • 1. The Logging module
    • Stage 1 – Basic use!
      • 1. Introduction:
      • 2. Log level
      • 3. Formater formats:
      • 4. Log level &format simulation use:
      • 5. Save the log information as a file:
    • The second stage – advanced version operation!
      • 1. The logging module also provides a way to modularize components — to configure the logger flexibly:
      • 2. Use of modular components:
        • (1) Usage steps:
        • (2) actual use of one (a logger corresponds to a log processor) :
        • (3) actual use of two (one logger corresponds to more [here is two] log processor) :
  • 2. In The End!

🔞 0. Preface:

  1. 👻👻 I believe that many beginners Python friends, encountered their own hard code error, you do your own way to solve the BUG is mostly – by adding a lot of print() function, little by little narrow down the scope, until find the BUG location and solve it! 👻 👻

For example, the following results t1 to result5 simulation friends worked hard to write five functions, results in the final call to achieve the ultimate function when it reported an error! Print () : print() : print();

result1 = 'The first function runs OK'
print(result1)
result2 = 'The second function runs OK'
print(result2)
result3 = 'The third function does not work'
print(result3)
result4 = 'The fourth function runs OK'
print(result4)
result5 = 'The fifth function runs OK'
print(result5)
Copy the code

Admittedly, this is also a way to solve bugs! However, when you find the BUG and solve it, you have to delete all the printf() statements one by one.

  1. 😬😬 So, here comes the logging module. Let me use it briefly – let’s see what this module does and what makes it great! (It doesn’t matter if you don’t understand, the following text is explained in detail!) 😬 😬

We changed all of the above pirntf() statements to logging.debug() statements and observed the output. At this point, there was no output — that is, there was no impact on our program for now!

import logging

logging.basicConfig(level=logging.INFO)

result1 = 'The first function runs OK'
logging.debug(result1)
result2 = 'The second function runs OK'
logging.debug(result1)
result3 = 'The third function runs OK'
logging.debug(result1)
result4 = 'The fourth function runs OK'
logging.debug(result1)
result5 = 'The fifth function runs OK'
logging.debug(result1)
Copy the code

We set the log level to DEBUG, that is, set the level to logging.DEBUG, and observe the output:

import logging

logging.basicConfig(level=logging.DEBUG)

result1 = 'The first function runs OK'
logging.debug(result1)
result2 = 'The second function runs OK'
logging.debug(result1)
result3 = 'The third function runs OK'
logging.debug(result1)
result4 = 'The fourth function runs OK'
logging.debug(result1)
result5 = 'The fifth function runs OK'
logging.debug(result1)
Copy the code

At this point, the message is output at the DEBUG level. This allows you to simply change the log level (by changing only one parameter value) to check whether the output is displayed or not, rather than repeatedly adding and deleting print() to check for errors. Isn’t it convenient?



3. 🐌🐌 I will try my best to make technical articles easy to understand/vivid and interesting, so as to ensure that every reader who wants to learn knowledge && read this article carefully will have something to gain. Of course, if you feel this article is ok after reading, really learned something, hope to give me a “like” and “collection”, this for meIt is very importantThank you! 🐌 🐌

Here comes the big point! Here comes the big point!! 💗 💗 💗

Let’s go into the world of logging module!!

1. The Logging module

Stage 1 – Basic use!

1. Introduction:

In software development, it is a good practice to log the performance of a program, which can help with error detection and system maintenance. The Python standard library has its own logging module. The logging function of the program directly calls the logging module of the standard library. Through the logging, the developer can clearly understand what events have occurred, including what errors have occurred.

2. Log level

Note: After the log level is specified, only log information greater than or equal to the specified log level is displayed!

Log level (level) describe
DEBUG Debug information, usually used to diagnose problems
INFO General information to confirm that the program is working as expected
WARNING Warning messages indicating that something unexpected has happened, or indicating that something may be going wrong, but the program continues to run
ERROR Error message, there are some problems in the program running, some functions of the program cannot be executed
CRITICAL Danger message, a serious error, cause the program cannot continue to run

Level size in logging: DEBUG<INFO<WARNING<ERROR<CRITICAL

3. Formater formats:

4. Log level &format simulation use:

import logging

# Set the output format
LOG_FORMAT = "Time: %(ascTime)s - Log level: %(LevelName)s - Log information: %(message)s"
Configure Logger -- log level & output format
logging.basicConfig(level=logging.WARNING, format=LOG_FORMAT)

# logging.level(message) Creates a level log
logging.debug("This is a debug log")
logging.info("This is a info log")
logging.warning("This is a warning log")
logging.error("This is a error log")
logging.critical("This is a critical log")
Copy the code

Only logs with a level greater than or equal to WARNING are displayed.

Note: logging.basicConfig() can only have one! If there are multiple entries – only the first entry will be valid!!

5. Save the log information as a file:

The above uses the final log information is output in the terminal – the computer/program/editor a close, the log information is lost! And we don’t do that in practice, so let’s see how to write to a file!

Tip: You can also specify how the file is written by specifying the value of the filemode parameter. (A, A +, etc.)

The second stage – advanced version operation!

If you are simply using Logging, then the above method is fine, but if you want to customize logging in depth, you need to know more about it!

1. The logging module also provides a way to modularize components — to configure the logger flexibly:

component instructions
Loggers (Loggers) The interface used directly by the provider (logging.basicConfig() in the base operation is configured for this component)
Handlers (log Handlers) Send the recorded log to the specified location (terminal print/save as a file)
Filters (log) Used to filter specific log records
Log Formatters Controls the output format of log information

The relationship between the components is shown in the figure below:

2. Use of modular components:

(1) Usage steps:

  1. Create a Logger object;
  2. Define a handler to decide where to send the log. StreamHandler — > Output to the console; FileHandler — > output to file;
  3. Set the log level and output Formatters.
  4. Add the handler to the corresponding Logger.

(2) actual use of one (a logger corresponds to a log processor) :

import logging

Create a Logger object;
my_logger = logging.Logger("first_logger")

# 2. Define a handler to decide where to send the log;
my_handler = logging.FileHandler('test.log')

# 3. Set the log level and output Formatters;
my_handler.setLevel(logging.INFO)
my_format = logging.Formatter("Time :%(asctime)s Log message :%(message)s Line number :%(lineno)d")

Add the handler to the logger.
my_handler.setFormatter(my_format)
my_logger.addHandler(my_handler)


# use:
my_logger.info("I am the logging component.")
Copy the code

(3) actual use of two (one logger corresponds to more [here is two] log processor) :

import logging

Create a logger object;
my_logger = logging.Logger("first_logger")


# First log handler
my_handler = logging.FileHandler('test.log')

my_handler.setLevel(logging.INFO)
my_format = logging.Formatter("Time :%(asctime)s Log message :%(message)s Line number :%(lineno)d")

my_handler.setFormatter(my_format)
my_logger.addHandler(my_handler)


# Second log handler
you_handler = logging.StreamHandler()

you_handler.setLevel(logging.DEBUG)
you_format = logging.Formatter("Time :%(asctime)s Log message :%(message)s Line number :%(lineno)d This is StreamHandler")

you_handler.setFormatter(you_format)
my_logger.addHandler(you_handler)


# use:
my_logger.info("I am the logging component.")
Copy the code

2. In The End!

Start from now, stick to it, a little progress a day, in the near future, you will thank you for your efforts!

This blogger will continue to update the basic crawler column and actual crawler column, carefully read this article friends, you can like the collection and comment out of your reading feeling. And can follow this blogger, in the days to read more reptilian!

If there are any mistakes or inappropriate words, please point them out in the comment section. Thank you! If reprint this article, please contact me to obtain my consent, and annotate the source and the name of this blogger, thank you!