How to debug the logging module code in Python

WBOY
Release: 2023-05-10 16:31:06
forward
1133 people have browsed it

1. Log hierarchy

Before you begin, it should be noted that there is a hierarchical structure in log records, called a log tree or logger hierarchy. The hierarchy consists of several levels, each level representing a different severity of log information. The most common levels are:

CRITICAL #A critical error occurred, the program may not be able to continue running.
ERROR #An error occurred that should be investigated.
WARNING # An indication that something unexpected happened or indicative of some problem in the near future.
INFO   #General information about the program's execution.
DEBUG   #Detailed information for debugging purposes.

二. Create a module

Let us create a python module named set_logging.py:

import logging
logger = logging.getLogger()
def set_logger():
  logger.setLevel(logging.INFO)
  handler = logging.StreamHandler()
  handler.setLevel(logger_level)
  formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  handler.setFormatter(formatter)
  logger.addHandler(handler)
Copy after login

To clarify the code, we create a module with the getLogger function Logger instance, and use setLevel to set the log level (DEBUG, INFO, etc.). The setLevel method of the logger is like a filter, which determines whether a log message should be processed and sent to the handler. For example, if we set the logger's level to INFO, then the logger will not send messages with level DEBUG to the handler because they have a lower severity than The lowest level to set on the logger. It only sends log messages of level INFO or higher (i.e. WARNING, ERROR, or CRITICAL) to the handler for processing .

We create a StreamHandler to send log information to a stream, such as the console or terminal. It is used to output log information for debugging purposes. We also set the level for the handler.

We do this because when the handler receives messages from the logger, it will compare those messages to its level and filter out lower severity messages before emitting. When we have different handlers:

logger.setLevel(logging.INFO)
file_handler = logging.FileHandler()
file_handler.setLevel(logging.ERROR)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.WARNING)

Since the logger's level is set to INFO, it only handles two Programs send log messages with level INFO or higher, but each handler only handles messages that meet or exceed its specified log level.

Back to our main example, we then create a formatter and add it to the handler. The formatter specifies the format of the log message, including timestamp, logger name, log level, and message. Finally, we add the handler to the logger.

Now in the code, we need to call set_logger like this:

import logging
from set_logging import set_logger
set_logger()
logger = logging.getLogger()
def roman_number(s: str) -> int:
    dic = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
    res = 0
    pre = None
    for char in s:
        res += dic.get(char)
        if dic.get(pre) and dic.get(pre) < dic.get(char):
            res -= 2 * dic.get(pre)
        pre = char
    logger.info("logging is awesome")
    return res
roman_number("IV")
Copy after login

Run this code , the results are as follows:

2023-03-04 02:26:57,619 - root - INFO - logging is awesome

3. Advantages of using logs

  • Level. A logger provides a way to set different log levels for different types of messages, such as DEBUG, INFO , WARNING, ERROR, and CRITICAL. This makes it easier to filter and prioritize log messages based on their severity. Of course, Printing can mimic the same behavior as logging, but it requires more hardcoding work and is not as flexible as logging.

  • Performance. Printing log information may Slower than using a logger, especially when processing large amounts of data or logging frequently.

  • Configurability. The logger provides a way to configure The application's logging behavior, such as log levels, log destinations, and log formats, without modifying the source code. This makes it easier to manage and maintain logging behavior over time.

  • Flexibility. The logger allows you to send log information to multiple destinations, such as the console, a file, or a database. This flexibility makes managing logs and analyzing them easier.

The above is the detailed content of How to debug the logging module code in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template