How to implement logging in Python?

In Python, you can utilize the built-in logging module to achieve logging functionality. Here is a simple example:

import logging

# 配置日志输出的格式和级别
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

# 打印不同级别的日志
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')

The output is as follows:

2019-08-01 10:30:00,000 - DEBUG - This is a debug message
2019-08-01 10:30:00,001 - INFO - This is an info message
2019-08-01 10:30:00,002 - WARNING - This is a warning message
2019-08-01 10:30:00,003 - ERROR - This is an error message
2019-08-01 10:30:00,004 - CRITICAL - This is a critical message

In the example above, we configured the logging output level as DEBUG using the basicConfig function, and defined the format of the log output. We then used methods like logging.debug, logging.info to print logs of different levels.

You can also redirect the log to a file instead of printing it to the console. Just set the filename parameter of the basicConfig function to a file path.

import logging

logging.basicConfig(level=logging.DEBUG, filename='mylog.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s')

logging.debug('This is a debug message')

In this way, the log information will be written to the mylog.log file.

In addition to the basic usage mentioned above, the logging module also offers more advanced functionalities such as configuring multiple loggers, setting log filters, and defining different log handlers. You can refer to the official documentation for more details: https://docs.python.org/3/library/logging.html.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds