在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模塊的信息,請參閱官方文檔。