在CentOS系統中,Python日志的配置通常是通過在Python應用程序中使用日志庫(如logging)來實現的。以下是一個簡單的示例,展示了如何在Python應用程序中配置日志:
sudo yum install python3
app.py
的Python文件,并添加以下代碼:import logging
# 配置日志
logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
# 獲取日志記錄器對象
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')
在這個示例中,我們使用basicConfig
方法配置了日志。filename
參數指定了日志文件的名稱(在這里是app.log
),filemode
參數指定了日志文件的打開模式(在這里是覆蓋寫入模式w
),format
參數定義了日志消息的格式。
python3 app.py
運行后,你會在當前目錄下看到一個名為app.log
的日志文件,其中包含了記錄的日志消息。
如果你想要更高級的日志配置,可以使用logging.config.fileConfig()
方法從單獨的配置文件中加載日志配置。以下是一個簡單的示例:
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', 'w')
[formatter_simpleFormatter]
format=%(name)s - %(levelname)s - %(message)s
datefmt=
app.py
文件,使用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')
python3 app.py
這樣,日志配置將根據logging.conf
文件中的設置進行應用。你可以根據需要修改配置文件,以實現更復雜的日志配置。