在Ubuntu系統中配置Python日志可以通過多種方式實現,以下是幾種常見的方法:
logging
模塊Python的logging
模塊提供了靈活的日志管理功能。你可以配置日志級別、格式和輸出目的地。以下是一個簡單的配置示例:
import logging
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
filename='example.log',
filemode='w'
)
# 記錄日志
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
logrotate
為了避免日志文件過大,可以使用logrotate
工具進行日志輪轉。首先,確保logrotate
已經安裝:
sudo apt update
sudo apt install logrotate
然后,可以創建或編輯/etc/logrotate.d/python
文件來配置日志輪轉規則:
/path/to/python/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 0640 root root
sharedscripts
postrotate
/path/to/python/restart_script.sh
endscript
}
同時,創建重啟腳本/path/to/python/restart_script.sh
:
#!/bin/bash
# 停止Python服務
sudo systemctl stop python
# 等待Python服務停止
sleep 5
# 啟動Python服務
sudo systemctl start python
確保腳本有可執行權限:
chmod +x /path/to/python/restart_script.sh
ELK Stack是一個強大的日志管理和分析工具。你可以將Python日志發送到Elasticsearch,然后使用Kibana進行分析和可視化。以下是簡要步驟:
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/elastic-7.x.list
sudo apt-get update && sudo apt-get install elasticsearch
wget -qO - https://artifacts.elastic.co/GPG-KEY-logstash | sudo apt-key add -
echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/logstash-7.x.list
sudo apt-get update && sudo apt-get install logstash
wget -qO - https://artifacts.elastic.co/GPG-KEY-kibana | sudo apt-key add -
echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/kibana-7.x.list
sudo apt-get update && sudo apt-get install kibana
創建/etc/logstash/conf.d/python.conf
文件:
input {
file {
path "/path/to/python/*.log"
start_position "beginning"
}
}
filter {
# 添加過濾器配置
}
output {
elasticsearch {
hosts ["localhost:9200"]
index "python-logs"
}
stdout
}
sudo systemctl start logstash
訪問 http://localhost:5601
,使用默認的用戶名和密碼(kibana_system / changeme
)登錄,然后配置索引模式以匹配你的日志數據。
通過以上方法,你可以在Ubuntu系統中有效地配置和管理Python日志。