Formatting Nginx Access Logs as JSON
While Nginx and Apache's log format has become pretty standard in the industry, it'd be nice if I could use the same tools for processing them as all my other logs, which are in JSON.
Luckily, Nginx has support for it using the
log_format main escape=json
The most obvious downside to this approach is that there are no
null values. Every key will always exist with a string value, and empty values are typically denoted with a
"-". So when processing, you'll need to make sure to exclude them.
escape=json only escapes characters for use in JSON strings (for example,
\/). The actual JSON formatting is done manually. So, when you're modifying the
log_format to add or remove keys, make sure it's still outputting valid JSON. Specifically ensure commas (
,) and speech marks (
") are in the right place.
Thanks for reading.