Nginx配置日志管理的最佳實踐包括以下幾點:
log_format custom '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log custom;
logrotate
工具定期分割日志文件,防止日志文件過大。/var/log/nginx/*.log {
daily
missingok
rotate 7
compress
notifempty
create 0640 root adm
}
error_log
和access_log
的級別,例如生產環境中通常設置為warn
或error
。error_log /var/log/nginx/error.log warn;
chmod 640 /var/log/nginx/*.log
chown root:adm /var/log/nginx/*.log
access_log /var/log/nginx/access.log custom buffer=32k flush=30s;
access_log /var/log/nginx/access.log custom async;
以下是一個綜合了上述最佳實踐的Nginx配置示例:
http {
log_format custom '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log custom buffer=32k flush=30s;
error_log /var/log/nginx/error.log warn;
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html index.htm;
}
}
}
通過遵循這些最佳實踐,可以有效地管理和維護Nginx日志,確保系統的穩定性和安全性。