Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a JSON log from nginx?

I'm trying to generate a JSON log from nginx.

I'm aware of solutions like this one but some of the fields I want to log include user generated input (like HTTP headers) which need to be escaped properly.

I'm aware of the nginx changelog entries from Oct 2011 and May 2008 that say:

*) Change: now the 0x7F-0x1F characters are escaped as \xXX in an    access_log. *) Change: now the 0x00-0x1F, '"' and '\' characters are escaped as \xXX    in an access_log. 

but this still doesn't help since \xXX is invalid in a JSON string.

I've also looked at the HttpSetMiscModule module which has a set_quote_json_str directive, but this just seems to add \x22 around the strings which doesn't help.

Any idea for other solutions to log in JSON format from nginx?

like image 662
Jules Olléon Avatar asked Jul 31 '14 01:07

Jules Olléon


People also ask

How do I get nginx logs?

By default, the access log is located at /var/log/nginx/access. log , and the information is written to the log in the predefined combined format. You can override the default settings and change the format of logged messages by editing the NGINX configuration file ( /etc/nginx/nginx.

How do I enable JSON logging?

To enable parsing JSON log, you add parse: json to a pipeline in the ClusterLogForwarder CR, as shown in the following example. When you enable parsing JSON logs by using parse: json , the CR copies the JSON-structured log entry in a structured field, as shown in the following example.

What is the format of Nginx logs?

The default log format in nginx is called "combined".

What is JSON logging?

JSON logging is a kind of structured logging, Meaning you'll have your log data parsed and stored in a structured JSON format.


2 Answers

Finally it looks like we have good way to do this with vanilla nginx without any modules. Just define:

log_format json_combined escape=json   '{'     '"time_local":"$time_local",'     '"remote_addr":"$remote_addr",'     '"remote_user":"$remote_user",'     '"request":"$request",'     '"status": "$status",'     '"body_bytes_sent":"$body_bytes_sent",'     '"request_time":"$request_time",'     '"http_referrer":"$http_referer",'     '"http_user_agent":"$http_user_agent"'   '}'; 

Note that escape=json was added in nginx 1.11.8. http://nginx.org/en/docs/http/ngx_http_log_module.html#log_format

like image 103
pva Avatar answered Sep 18 '22 08:09

pva


You can try to use that one https://github.com/jiaz/nginx-http-json-log - addition module for Nginx.

like image 30
Seva Poliakov Avatar answered Sep 20 '22 08:09

Seva Poliakov