在Ubuntu上配置Python日志系统,可参考以下方法:
logging模块通过代码或配置文件灵活设置日志级别、格式和输出目标。
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
filename='app.log',
filemode='a' # 'a'为追加模式,'w'为覆盖模式
)
logging.info('This is an info message')
logging.conf文件,定义日志处理器(如控制台、文件)、格式和级别,通过logging.config.fileConfig()加载。[loggers]
keys=root
[handlers]
keys=consoleHandler,fileHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler,fileHandler
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=('app.log', 'a')
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
使用系统工具logrotate管理日志文件,设置按天轮转、保留天数、压缩等规则。
sudo apt install logrotate
sudo nano /etc/logrotate.d/myapp
添加以下内容(按需修改路径和参数):/var/log/myapp/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 0640 root root
}
适合大规模日志分析,需安装Elasticsearch、Logstash、Kibana。
# 安装Elasticsearch
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 /etc/apt/sources.list.d/elastic-7.x.list
sudo apt update && sudo apt install elasticsearch
# 安装Logstash
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 /etc/apt/sources.list.d/logstash-7.x.list
sudo apt install logstash
# 安装Kibana
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 /etc/apt/sources.list.d/kibana-7.x.list
sudo apt install kibana
/etc/logstash/conf.d/myapp.conf,指定日志路径和输出到Elasticsearch:input {
file {
path => "/var/log/myapp/*.log"
start_position => "beginning"
}
}
output {
elasticsearch {
hosts => ["localhost:9200"]
index => "myapp-logs"
}
}
syslog),而非直接文件。concurrent-log-handler库)。以上方法可根据项目需求选择,基础场景推荐logging模块,复杂场景可结合logrotate或ELK。