nginx中用JSON格式记录日志的配置示例

nginx的日志配置可以参见《nginx日志配置指令详解》一文。如果要想以json格式记录nginx日志以便logstash分析,该如何指定日志格式呢?可以按照下面的格式来实现。

定义nginx日志格式:


log_format logstash_json '{ "@timestamp": "$time_local", '

                         '"@fields": { '

                         '"remote_addr": "$remote_addr", '

                         '"remote_user": "$remote_user", '

                         '"body_bytes_sent": "$body_bytes_sent", '

                         '"request_time": "$request_time", '

                         '"status": "$status", '

                         '"request": "$request", '

                         '"request_method": "$request_method", '

                         '"http_referrer": "$http_referer", '

                         '"body_bytes_sent":"$body_bytes_sent", '

                         '"http_x_forwarded_for": "$http_x_forwarded_for", '

                         '"http_user_agent": "$http_user_agent" } }';

指定记录日志格式:


access_log  /data/logs/nginx/www.nhooo.com.access.log  logstash_json;

日志输出如下:

不利于阅读。复制到http://jsonlint.com/美化下格式。