在Debian系統上管理Nginx日志,通常涉及以下幾個關鍵步驟:
/etc/nginx/nginx.conf
。nano
或 vim
)打開文件。http
塊中定義日志格式。例如: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;
error_log /var/log/nginx/error.log debug;
}
custom
是自定義的日志格式名稱,包含客戶端IP地址、請求時間、HTTP狀態碼等信息。http
塊中指定訪問日志和錯誤日志的路徑。server {
listen 80;
server_name example.com;
access_log /var/log/nginx/example.com.access.log custom;
error_log /var/log/nginx/example.com.error.log debug;
location / {
root /var/www/html;
index index.html index.htm;
}
}
sudo nginx -s reload
重新加載Nginx以應用更改。ls -l /var/log/nginx/
命令查看日志文件。tail -f /var/log/nginx/access.log
實時查看訪問日志。tail -f /var/log/nginx/error.log
實時查看錯誤日志。為了避免日志文件過大,可以使用 logrotate
工具進行日志輪轉。
logrotate
配置文件:/etc/logrotate.d/nginx
文件用于配置Nginx日志輪轉。/var/log/nginx/*.log {
daily
missingok
rotate 7
compress
notifempty
create 0640 www-data adm
}
logrotate
配置:logrotate
配置之前,建議先測試配置文件是否有語法錯誤:sudo logrotate -d /etc/logrotate.d/nginx
logrotate
配置:logrotate
配置以應用更改:sudo logrotate -f /etc/logrotate.d/nginx
tail -f
命令實時查看日志文件。grep
命令搜索特定內容:sudo tail -f /var/log/nginx/access.log | grep --color=auto "200"
nginx-ui
等圖形界面工具,通過Web界面管理和分析Nginx日志。git clone https://github.com/0xJacky/nginx-ui.git
cd nginx-ui
docker build -t nginx-ui .
docker run -d -p 8080:80 -v /etc/nginx:/etc/nginx -v /var/log/nginx:/var/log/nginx nginx-ui
ngxtop
等工具實時監控和分析Nginx日志文件。sudo apt-get install python3-pip
sudo pip3 install ngxtop
ngxtop -l /var/log/nginx/access.log
通過以上步驟,你可以在Debian系統上高效地管理和監控Nginx日志,確保日志文件不會占用過多磁盤空間,并且可以實時監控和分析日志。