Mỗi request vào Nginx sẽ:
Khi traffic lớn (10k–100k request/giây):
Kết quả là:
Nếu bạn có nhiều request static như CSS, JS, ảnh:
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2)$ {
access_log off;
log_not_found off;
}
Việc này có thể giảm 50–80% log write nếu website nhiều asset.
Nếu hệ thống internal API hoặc không cần trace:
access_log off;
Áp dụng trong server hoặc location.
Format mặc định khá dài:
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
Bạn có thể rút gọn:
log_format minimal '$remote_addr "$request" $status $body_bytes_sent'; access_log /var/log/nginx/access.log minimal;
Giảm CPU xử lý format string đáng kể.
Thay vì ghi từng dòng xuống disk:
access_log /var/log/nginx/access.log minimal buffer=256k flush=5s;
Ý nghĩa:
Giảm I/O rất nhiều khi traffic cao.
⚠ Lưu ý: nếu server crash, có thể mất vài KB log cuối.
access_log syslog:server=127.0.0.1:514 minimal;
Ưu điểm:
Phù hợp khi dùng ELK / Loki / Splunk.
Mặc định nhiều server để:
error_log /var/log/nginx/error.log notice;
Nên giảm xuống:
error_log /var/log/nginx/error.log warn;
Hoặc production nặng:
error_log /var/log/nginx/error.log error;
Tránh ghi quá nhiều dòng debug.
Chỉ log khi status >= 400:
map $status $loggable {
~^[23] 0;
default 1;
}access_log /var/log/nginx/access.log minimal if=$loggable;
Giảm 80–95% log nếu hệ thống ổn định.
Logging chỉ là một phần. Khi quá tải, cần tối ưu toàn hệ thống.
worker_processes auto; worker_rlimit_nofile 200000;
events {
worker_connections 65535;
multi_accept on;
use epoll;
}
keepalive_timeout 15; keepalive_requests 1000;
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;server {
location / {
limit_req zone=one burst=20 nodelay;
}
}
Nếu CPU 100% và load tăng:
Bạn nên monitor:
Các công cụ phổ biến:
Nếu chỉ cần nhanh gọn:
htop top vmstat 1
Production traffic cao thường:
Hoặc dùng:
Nếu bạn đang bị quá tải, hãy áp dụng theo thứ tự:
worker_processes auto;
worker_rlimit_nofile 200000;events {
worker_connections 65535;
multi_accept on;
use epoll;
}http {
log_format minimal '$remote_addr "$request" $status $body_bytes_sent'; map $status $loggable {
~^[23] 0;
default 1;
} access_log /var/log/nginx/access.log minimal buffer=512k flush=5s if=$loggable;
error_log /var/log/nginx/error.log warn; keepalive_timeout 15;
keepalive_requests 1000;
}
Kết luận quan trọng
Trong môi trường traffic cao, logging không được cấu hình đúng có thể chiếm 20–40% CPU và gây nghẽn I/O.
Tối ưu access log thường là bước nhanh nhất để cứu một server đang quá tải.