How to debug the logging module code in Python
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)
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")
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
, andCRITICAL
. 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
