A tutorial on using the logger module in Python

  Reference module:

  https://www.digitalocean.com/community/tutorials/how-to-use-logging-in-python-3

  logger is a built-in module of python, which is used to output the running status of the code during running, which greatly facilitates our debugging process. References list the advantages of using logger over print:

  1. Using print is difficult to distinguish from the normal output of the code

  2. There is no way to disable or remove all debug statements at once using print

  3. Using print cannot generate a uniform and readable logger log file

  In the simplest usage scenario, first import the logging package with the following code, and then set the logger level to DEBUG:

import logging

logging.basicConfig(level=logging.DEBUG)

  Then replace print with logging where you need to output debug statements in the code:

logging.debug("This is for debug.")

  In fact, the above usage is straightforward but not standard. The standard way is to define a logger, so that when entering the logger log, the name of the defined logger will be displayed, which is easier to read:

logger1 = logging.getLogger("module_1")
logger2 = logging.getLogger("module_2")

logger1.debug("Module 1 debugger")
logger2.debug("Module 2 debugger")

  If you want to output the logging statement to a file, you only need to add a filename parameter in the basicConfig section, so that the result will be output to the log file:

logging.basicConfig(filename="test.log", level=logging.DEBUG)

  These are the basic usages. In fact, logging obviously has not only debug but also many other levels, as shown in the following table:

   The default level is 30, and if it is adjusted to 10, all files greater than or equal to 10 will be output.

Guess you like

Origin blog.csdn.net/weixin_43590796/article/details/131017122