Access Log

Access Log #

Access log mencatat setiap request HTTP yang diproses Nginx — siapa yang mengakses, apa yang diminta, kapan, berapa lama, dan apa yang dikembalikan. Ini adalah sumber data utama untuk monitoring trafik, debugging masalah, dan analisis penggunaan.

Format Log Default #

Nginx menggunakan format combined sebagai default, yang merupakan format Apache combined log — format yang sudah dipahami oleh hampir semua tools analisis log:

http {
    log_format combined '$remote_addr - $remote_user [$time_local] '
                        '"$request" $status $body_bytes_sent '
                        '"$http_referer" "$http_user_agent"';

    access_log /var/log/nginx/access.log combined;
}

Contoh baris log dalam format ini:

203.0.113.42 - john [15/Jan/2024:10:30:45 +0700] "GET /api/users HTTP/1.1" 200 1234 "https://example.com/dashboard" "Mozilla/5.0 (Macintosh; ...)"

Setiap field:

203.0.113.42          → $remote_addr     IP klien
-                     → $remote_user     username (jika pakai basic auth, '-' jika tidak)
john                  → $remote_user     username
[15/Jan/2024:...]     → $time_local      waktu request
"GET /api/users ..."  → $request         method, path, protokol
200                   → $status          HTTP status code
1234                  → $body_bytes_sent ukuran body response (bytes)
"https://..."         → $http_referer    halaman sebelumnya
"Mozilla/5.0..."      → $http_user_agent browser/client

Mengkonfigurasi access_log #

http {
    # Log ke file dengan format tertentu
    access_log /var/log/nginx/access.log combined;

    # Matikan access log sepenuhnya (tidak disarankan untuk production)
    access_log off;

    # Log ke syslog
    access_log syslog:server=unix:/var/log/nginx.sock combined;

    server {
        # Override log per virtual host
        access_log /var/log/nginx/mysite-access.log combined;

        location /health {
            # Jangan log endpoint health check
            access_log off;
            return 200 'ok';
        }

        location ~* \.(ico|css|js|png|jpg|woff2)$ {
            # Jangan log akses ke file statis
            access_log off;
            expires 1y;
        }
    }
}

Format Log Kustom #

Format default sudah cukup untuk analisis dasar, tapi untuk debugging reverse proxy atau performa, kamu butuh informasi lebih:

http {
    # Format untuk reverse proxy — tambahkan info backend
    log_format proxy_log '$remote_addr - [$time_local] '
                         '"$request" $status $body_bytes_sent '
                         'rt=$request_time '
                         'uaddr=$upstream_addr '
                         'ust=$upstream_status '
                         'urt=$upstream_response_time '
                         'cache=$upstream_cache_status';

    # Format JSON — mudah diparsing oleh log aggregator (ELK, Loki, dll.)
    log_format json_log escape=json
        '{'
            '"time":"$time_iso8601",'
            '"remote_addr":"$remote_addr",'
            '"method":"$request_method",'
            '"uri":"$uri",'
            '"status":$status,'
            '"bytes_sent":$body_bytes_sent,'
            '"request_time":$request_time,'
            '"upstream_response_time":"$upstream_response_time",'
            '"http_referer":"$http_referer",'
            '"http_user_agent":"$http_user_agent",'
            '"upstream_addr":"$upstream_addr",'
            '"upstream_cache_status":"$upstream_cache_status"'
        '}';

    server {
        access_log /var/log/nginx/access.log proxy_log;
        # atau
        access_log /var/log/nginx/access.json json_log;
    }
}

Format JSON sangat berguna jika kamu menggunakan log aggregator seperti Elasticsearch/Logstash/Kibana (ELK), Grafana Loki, atau Datadog — mereka bisa langsung mem-parse JSON tanpa konfigurasi parser tambahan.


Buffering Log untuk Performa #

Setiap baris log yang ditulis adalah operasi disk. Untuk server dengan trafik tinggi, ini bisa menjadi bottleneck. Nginx bisa mem-buffer entri log di memori sebelum menulisnya ke disk sekaligus:

http {
    # buffer=32k: kumpulkan log di buffer 32KB sebelum flush ke disk
    # flush=5s: paksa flush setiap 5 detik meski buffer belum penuh
    access_log /var/log/nginx/access.log combined buffer=32k flush=5s;
}

Trade-off: dengan buffering, ada risiko kehilangan beberapa entri log terakhir jika Nginx crash sebelum buffer di-flush. Untuk sebagian besar aplikasi, ini trade-off yang bisa diterima demi performa.


Log Per Virtual Host #

Memisahkan log per virtual host memudahkan debugging ketika ada banyak site:

# /etc/nginx/conf.d/example.com.conf
server {
    listen 443 ssl;
    server_name example.com;

    access_log /var/log/nginx/example.com-access.log combined;
    error_log  /var/log/nginx/example.com-error.log warn;

    # ...
}

# /etc/nginx/conf.d/api.example.com.conf
server {
    listen 443 ssl;
    server_name api.example.com;

    access_log /var/log/nginx/api.example.com-access.log proxy_log;
    error_log  /var/log/nginx/api.example.com-error.log warn;

    # ...
}

Dengan struktur ini, ketika ada laporan error di api.example.com, kamu langsung buka file log yang tepat tanpa perlu filter dari satu file log besar.


Analisis Log Cepat dari Command Line #

# 10 IP yang paling banyak melakukan request
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10

# 10 URL yang paling sering diakses
awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10

# Hitung jumlah request per status code
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn

# Response time rata-rata (untuk format yang menyertakan $request_time)
awk '{print $NF}' /var/log/nginx/access.log | \
    awk -F= '{sum += $2; count++} END {print "avg:", sum/count, "s"}'

# Tampilkan hanya request yang lambat (> 1 detik)
awk '$NF > 1' /var/log/nginx/access.log | tail -20

Ringkasan #

  • Format default combined sudah cukup untuk analisis umum. Tambahkan $request_time, $upstream_response_time, dan $upstream_cache_status untuk debugging performa.
  • Format JSON memudahkan integrasi dengan log aggregator modern (ELK, Loki, Datadog).
  • access_log off untuk endpoint health check dan file statis — mengurangi noise dan beban disk.
  • buffer=32k flush=5s mengurangi operasi disk tanpa risiko signifikan kehilangan data log.
  • Pisahkan log per virtual host agar debugging lebih mudah dan terfokus.

← Sebelumnya: Security Headers   Berikutnya: Error Log →

About | Author | Content Scope | Editorial Policy | Privacy Policy | Disclaimer | Contact