在CentOS上配置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('root')
# 使用日志记录器记录消息
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')
现在,当你运行这个Python脚本时,它将根据logging.conf
文件中的配置记录日志。
注意:确保logging.conf
文件与你的Python脚本位于同一目录中,或者提供正确的文件路径。