Table of Contents
To make your Nginx logs easier to process for tools like Elasticsearch or Logstash, you should configure them to output in JSON format.
Step 1: Define the JSON Format
Open your nginx.conf file and add the following log_format block within the http section:
log_format json escape=json
'{'
'"@timestamp":"$time_iso8601",'
'"message":"$remote_addr - $remote_user [$time_local] \"$request\" $status $body_bytes_sent \"$http_referer\" \"$http_user_agent\"",'
'"tags":["nginx_access"],'
'"realip":"$remote_addr",'
'"proxyip":"$http_x_forwarded_for",'
'"remote_user":"$remote_user",'
'"contenttype":"$sent_http_content_type",'
'"bytes":$body_bytes_sent,'
'"duration":"$request_time",'
'"status":"$status",'
'"request":"$request",'
'"method":"$request_method",'
'"referrer":"$http_referer",'
'"useragent":"$http_user_agent"'
'}';
Step 2: Apply the Format to Your Logs
Once the format is defined, you need to tell your virtual host (vhost) to use it. Add the following line to your server block configuration:
access_log /var/log/nginx/access.json json;
Step 3: Test and Reload
Before restarting, always test your Nginx configuration for syntax errors:
nginx -t
If the test is successful, reload Nginx to apply the changes:
systemctl reload nginx