ubuntu

Ubuntu上Python日志如何配置

小樊
35
2025-03-30 17:13:54
栏目: 编程语言

在Ubuntu上配置Python日志,你可以使用Python的内置logging模块。以下是一个简单的示例,展示了如何配置日志记录器、处理器和格式化程序。

首先,创建一个名为logging.conf的配置文件,用于存储日志配置信息:

[loggers]
keys=root

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

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

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S

这个配置文件定义了一个名为root的记录器,它将日志级别设置为DEBUG。它还定义了一个名为consoleHandler的处理器,它将日志输出到控制台,并使用名为simpleFormatter的格式化程序。

接下来,在你的Python脚本中,使用logging.config.fileConfig()函数加载配置文件:

import logging
import logging.config

# 加载配置文件
logging.config.fileConfig('logging.conf')

# 获取记录器
logger = logging.getLogger(__name__)

# 记录不同级别的日志
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')

运行此脚本后,你应该会在控制台上看到类似以下的输出:

2022-01-01 12:34:56,789 - __main__ - DEBUG - This is a debug message
2022-01-01 12:34:56,790 - __main__ - INFO - This is an info message
2022-01-01 12:34:56,790 - __main__ - WARNING - This is a warning message
2022-01-01 12:34:56,790 - __main__ - ERROR - This is an error message
2022-01-01 12:34:56,790 - __main__ - CRITICAL - This is a critical message

你可以根据需要修改logging.conf文件,以更改日志级别、处理器和格式化程序。更多关于logging模块的信息,请参阅官方文档

0
看了该问题的人还看了