在Python中,可以使用logging模块来配置日志记录。以下是一个简单的例子:
import logging# 配置日志记录logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')# 创建logger对象logger = logging.getLogger()# 记录日志消息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')在这个例子中,我们使用basicConfig()函数来配置日志记录级别和格式,然后创建了一个logger对象来记录不同级别的日志消息。
你也可以使用配置文件来配置日志记录,例如:
import loggingimport logging.config# 读取配置文件logging.config.fileConfig('logging.conf')# 创建logger对象logger = logging.getLogger()# 记录日志消息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')在上面的例子中,我们使用fileConfig()函数来读取配置文件logging.conf,然后创建logger对象来记录日志消息。
配置文件logging.conf的内容可以像这样:
[loggers]keys=root[handlers]keys=consoleHandler[formatters]keys=sampleFormatter[logger_root]level=DEBUGhandlers=consoleHandler[handler_consoleHandler]class=StreamHandlerlevel=DEBUGformatter=sampleFormatterargs=(sys.stdout,)[formatter_sampleFormatter]format=%(asctime)s - %(levelname)s - %(message)s 

