在CentOS系统中,配置Python日志可以通过使用Python的内置logging模块来实现。以下是一个简单的示例,展示了如何配置Python日志:
logging.conf的配置文件,用于存储日志配置信息。在这个文件中,你可以定义日志级别、日志格式、日志文件名等。[loggers]
keys=root
[handlers]
keys=fileHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=fileHandler
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=('app.log', 'a')
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S
在这个配置文件中,我们定义了一个名为root的logger,它的日志级别为DEBUG。我们还定义了一个名为fileHandler的handler,它将日志写入到名为app.log的文件中。最后,我们定义了一个名为simpleFormatter的formatter,用于设置日志的输出格式。
logging.config.fileConfig()函数加载配置文件:import logging
import logging.config
# 加载日志配置文件
logging.config.fileConfig('logging.conf')
# 获取logger对象
logger = logging.getLogger(__name__)
# 使用logger记录日志
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脚本时,日志信息将被写入到app.log文件中,并按照你在配置文件中定义的格式显示。
注意:确保logging.conf文件与你的Python脚本位于同一目录下,或者提供正确的文件路径。