在Linux系統中使用Swagger進行API日志記錄,通常涉及以下幾個步驟:
sudo apt-get update
sudo apt-get install swagger[core]
生成Swagger文檔:確保你的API項目已經集成了Swagger,并能生成OpenAPI規范文件(通常是swagger.json
或openapi.json
)。
配置API請求日志:
log_format api_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$http_x_forwarded_for" rt=$request_time uct="$upstream_connect_time" '
'uht="$upstream_header_time" urt="$upstream_response_time"';
access_log /var/log/nginx/api_access.log api_log;
日志收集與處理:
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/nginx/api_access.log
- /var/log/your-app/api.log
output.elasticsearch:
hosts: ["localhost:9200"]
filter {
grok {
match => { "message" => '\[%{TIMESTAMP_ISO8601:timestamp}\] %{IP:client_ip} "%{WORD:method} %{URIPATH:api_path} HTTP/%{NUMBER:http_version}" %{NUMBER:status} %{NUMBER:bytes_sent}' }
}
date {
match => ["timestamp", "ISO8601"]
target => "@timestamp"
}
mutate {
add_field => { "api_endpoint" => "%{method} %{api_path}" }
}
}
日志管理工具:
logrotate
,來管理日志文件的存儲和清理,防止磁盤空間被耗盡。sudo vi /etc/logrotate.d/swagger-editor
/var/log/swagger/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 644 root root
sharedscripts
postrotate
/usr/bin/systemctl reload your-service.service > /dev/null
endscript
}
監控和報警:集成監控和報警,使用Swagger的API監控功能結合Linux的監控工具(如Prometheus和Grafana)來實現API日志的實時監控和報警。
通過以上步驟,你可以在Linux系統上有效地記錄和分析Swagger相關的API日志,確保系統的穩定運行和問題的快速排查。