在CentOS系統下,配置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
的記錄器,它的日志級別為DEBUG
。我們還定義了一個名為fileHandler
的處理器,它將日志寫入到app.log
文件中。最后,我們定義了一個名為simpleFormatter
的格式化器,用于定義日志的輸出格式。
logging.config.fileConfig()
函數加載配置文件: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')
現在,當你運行這個Python腳本時,日志信息將被寫入到app.log
文件中,并按照你在配置文件中定義的格式顯示。
注意:確保logging.conf
文件的路徑正確,或者將其放在與Python腳本相同的目錄下。