温馨提示×

python中log函数如何配置

小樊
85
2024-08-21 06:11:31
栏目: 编程语言

在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 logging
import 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=DEBUG
handlers=consoleHandler

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=sampleFormatter
args=(sys.stdout,)

[formatter_sampleFormatter]
format=%(asctime)s - %(levelname)s - %(message)s

0