Logging module in Python

🔞 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 runs not OK' print(result3) result4 Print (result4) result5 = 'run 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 = 'run the first function OK' logging.debug(result1) result2 = Logging.debug (result1) result3 = 'the third function runs OK' logging.debug(result1) result4 =' The fourth function runs OK' Logging.debug (result1) result5 = 'run the fifth function 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 = 'run the first function OK' logging.debug(result1) result2 = Logging.debug (result1) result3 = 'the third function runs OK' logging.debug(result1) result4 =' The fourth function runs OK' Logging.debug (result1) result5 = 'run the fifth function 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?

  1. 🐌🐌 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 is very important to me, thank 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 LOG_FORMAT = "time: %(asctime)s - log level: %(levelName)s - log information: %(asctime) Logging.basicconfig (level= logging.warning, 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 # 1. 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 corresponding Logger. 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_handler = logging.FileHandler('test.log') My_handler.setlevel (logging.info) my_format = logging.formatter (" time :%(asctime)s" %(lineno)d") my_handler. SetFormatter (my_format) my_logger.addHandler(my_handler) # StreamHandler() you_handler.setlevel (logging.debug) you_format = logging.formatter (" time :%(asctime)s %(lineno)d ") you_handler.setformatter (you_format) my_logger.addHandler(you_handler) # My_logger.info (" I am a logging component ")Copy the code

2.InThe End!

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