How to use the logging module for logging in Python 3.x

WBOY
Release: 2023-07-30 13:51:49
Original
1247 people have browsed it

How to use the logging module for logging in Python 3.x

Introduction:
In the software development process, logging is an important component. By recording program running status and various events, troubleshooting, performance analysis and system monitoring can be easily performed. The logging module in Python provides powerful and flexible logging functions, which can easily generate and manage logs.

1. Overview of logging module
Logging is a built-in module of Python that provides complete logging functions. By using the logging module, you can define various output formats and output targets, and you can also easily control the log level, and flexibly record and display log information as needed.

2. Basic logging
The following example demonstrates how to use the logging module for basic logging in Python:

import logging

# 配置日志记录器
logging.basicConfig(level=logging.DEBUG, 
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# 创建日志记录器
logger = logging.getLogger('my_logger')

# 记录不同级别的日志
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')
Copy after login

In the above code, first pass basicConfig The function configures the global logger, specifies the logging level as DEBUG, and specifies the log format. Then create a specific logger named 'my_logger' through the getLogger function. Afterwards, through different levels of methods, such as debug, info, warning, error and critical, respectively Different levels of log information are recorded.

3. Log level and output format control
The logging module provides multiple levels of logging, including DEBUG, INFO, WARNING# There are five levels: ##, ERROR and CRITICAL, increasing from low to high. You can control the verbosity of logging by setting the levels of the logger and different processors.

import logging

# 配置日志记录器
logging.basicConfig(level=logging.WARNING, 
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# 创建日志记录器
logger = logging.getLogger('my_logger')

# 创建文件处理器
file_handler = logging.FileHandler('log.txt')
file_handler.setLevel(logging.DEBUG)

# 创建控制台处理器
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.ERROR)

# 设置处理器的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)

# 添加处理器到记录器
logger.addHandler(file_handler)
logger.addHandler(console_handler)

# 记录不同级别的日志
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')
Copy after login

In the above code, first set the global logging level to

WARNING through the basicConfig function. Then use the getLogger function to create a logger named 'my_logger'. Then two processors are created, one is the file processor that writes to the file, and the other is the console processor that outputs to the console. By setting the processor level, you can control the log output levels of files and consoles respectively. Finally, add the handler to the logger via the addHandler method.

4. More advanced configuration

The logging module also provides more advanced configuration options, such as log output location, file splitting, log rotation, log auditing, etc. The following is an example of using RotatingFileHandler for log file rotation:

import logging
from logging.handlers import RotatingFileHandler

# 创建日志记录器
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)

# 创建轮转文件处理器
file_handler = RotatingFileHandler('log.txt', maxBytes=1024, backupCount=5)

# 设置处理器的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)

# 添加处理器到记录器
logger.addHandler(file_handler)

# 记录不同级别的日志
for i in range(10):
    logger.debug('This is debug message %d' % i)
Copy after login
In the above code, a file handler is created through the

RotatingFileHandler class and the maximum file size is specified to be 1024 words. section, the number of backup files retained is 5. In this way, when the log file reaches the maximum size, it will be automatically split into multiple files while retaining the specified number of backup files.

Summary:

This article introduces the basic method of using the logging module for logging in Python 3.x. By using different levels of methods, different levels of log information can be recorded conveniently. By configuring different processors and formats, you can flexibly control the output location and format of the log. At the same time, the logging module also provides more advanced configuration options, such as file splitting, log rotation, etc., to meet more complex logging needs. For beginners of logging, starting with basic methods and gradually mastering more advanced configuration options will help improve the maintainability and debugging efficiency of the code.

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

Related labels:
source:php.cn
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