在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日志。