I’ve recently decided that it’s a good idea to output server logs in JSON format. To this end, today I took some time to figure out how to do this for Nginx. The log_format
parameter is the one you want to use, I simply added another named format to the http
section of nginx.conf
, which then allows the named format to be used in any other config file. Here’s what I whipped up – this is just the default main
format ported to JSON:
log_format json '{'
'"remote_addr": "$remote_addr",'
'"remote_user": "$remote_user",'
'"time_local": "$time_local",'
'"request": "$request",'
'"status": $status,'
'"body_bytes_sent": $body_bytes_sent,'
'"http_referer": "$http_referer",'
'"http_user_agent": "$http_user_agent",'
'"http_x_forwarded_for": "$http_x_forwarded_for"'
'}';
I formatted it one row per parameter in the config file, as it’s easier for me to read, but Nginx will concatenate all those separate strings into one line in the log file. Once this is done, use the format in any of places where it’s accepted, for example:
access_log /path/to/file/access.log json;
For more details on all this stuff, check out the online documentation for Nginx’s logging module.