SoFunction
Updated on 2025-05-17

Detailed explanation of Python logging module usage examples

Python'sloggingModule is a flexible and powerful logging tool that is widely used in application debugging, operation monitoring and problem investigation. It provides rich functions, including multi-level logging, multiple output methods, flexible format configuration, etc. The following is a detailed introduction:

1. Why use the logging module?

  • AlternativeprintprintStatements are only suitable for simple debugging, andloggingSupports persistence, level control, asynchronous writing, etc.
  • Grading log: Distinguish logs (such as DEBUG, INFO, ERROR) according to their importance to facilitate filtering of information.
  • Flexible output: It can be output to console, files, network, etc. at the same time.
  • Thread safety: Suitable for multi-threaded/multi-process environments.

2. Core components

Logger(Recordor)
The interface directly called by the application is responsible for generating logs.

  • pass(name)Get or create a Logger instance.
  • Support hierarchical structures (e.g.''Inherit parent configuration).

Handler(processor)
Determines the output location of the log (such as console, files, emails, etc.).

  • Commonly used Handler:
    • StreamHandler: Output to stream (such as console).
    • FileHandler: Output to file.
    • RotatingFileHandler: Scroll log files by size.
    • TimedRotatingFileHandler: Scroll the log file by time.
    • SMTPHandler: Send email.

Filter(Filter)
Provides finer-grained log filtering (such as logging only specific keywords).

Formatter(Format)
Defines the output format of the log (time, level, message, etc.).

Common format fields:

'%(asctime)s - %(name)s - %(levelname)s - %(message)s'

3. Log level

There are 6 levels from low to high (logs below the set level will be ignored):

level Value illustrate
DEBUG 10 Detailed debugging information
INFO 20 Normal operation information of the program
WARNING 30 Potential problem, but the program still runs
ERROR 40 Serious errors affect some functions
CRITICAL 50 Fatal error that may cause program termination

4. Basic usage steps

Create a Logger

import logging
logger = (__name__)  # It is recommended to use the module name as the Logger name()        # Set the minimum level of record

Configure Handler and Formatter

# Create a console Handlerconsole_handler = ()
console_handler.setLevel()  # The console only outputs WARNING and above levels# Create a file Handlerfile_handler = ('')
file_handler.setLevel()      # File records all DEBUG and above levels# Define Formatterformatter = ('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
file_handler.setFormatter(formatter)
# Add Handler to Logger(console_handler)
(file_handler)

Logging

('Debug information')
('Program Start')
('Insufficient disk space')
('Request timed out')

5. Quick configuration (basicConfig)

Quick configuration for simple scenarios:

import logging
(
    level=,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        (''),
        ()
    ]
)
('Warning message')

6. Advanced usage

Configuration file or dictionary
useModules are configured via file or dictionary:

import 
config = {
    'version': 1,
    'formatters': {
        'default': {'format': '%(asctime)s - %(levelname)s - %(message)s'}
    },
    'handlers': {
        'console': {
            'class': '',
            'formatter': 'default',
            'level': 'DEBUG'
        }
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO'
    }
}
(config)

Capture exception information
useLog exception stack:

try:
    1 / 0
except Exception:
    ('Exception occurred:')

Log spread
Child Logger Passes logs to parent Logger by default. Available = Falseclosure.

7. Frequently Asked Questions

Repeat log
Reason: Adding Handler orbasicConfigCalled multiple times.
Solution: Make sure the Handler is added only once, or inbasicConfigSettings inforce=True

Performance optimization
Avoid recording low-level logs (such as DEBUG) in high-frequency codes, and check the level in advance:

if ():
    (f'Time-consuming operation: {time_consuming()}')

8. Summary

loggingThe module meets the log needs from simple to complex through flexible configuration and hierarchy mechanisms. Mastering its core components (Logger, Handler, Formatter) and level control can significantly improve the maintainability of the program. It is recommended to replace it in the projectprint, use logs reasonably for debugging and monitoring.

This is the end of this article about the detailed explanation of the Python logging module usage examples. For more related contents of Python logging module usage, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!