nginx log以JSON格式记录

默北 Nginx528,6644字数 789阅读2分37秒阅读模式

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

定义nginx日志格式:文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-log-records-in-json-format/

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" } }';

指定记录日志格式:文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-log-records-in-json-format/

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

日志输出如下:文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-log-records-in-json-format/

json文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-log-records-in-json-format/

 文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-log-records-in-json-format/

不利于阅读。复制到http://jsonlint.com/美化下格式。文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-log-records-in-json-format/

 文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-log-records-in-json-format/

json文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-log-records-in-json-format/ 文章源自运维生存时间-https://www.ttlsa.com/nginx/nginx-log-records-in-json-format/

weinxin
我的微信
微信公众号
扫一扫关注运维生存时间公众号,获取最新技术文章~
默北
  • 本文由 发表于 21/07/2014 01:00:33
  • 转载请务必保留本文链接:https://www.ttlsa.com/nginx/nginx-log-records-in-json-format/
评论  5  访客  5
    • 汪仁君
      汪仁君 1

      Parse error on line 16:
      …ild/JSS15J)" }}{ "Timestamp": "
      ———————^
      Expecting ‘EOF’, ‘}’, ‘,’, ‘]’

        • 默北
          默北

          @ 汪仁君 格式出错

            • 汪仁君
              汪仁君 1

              @ 默北 是的,那请问我改如何修正呢?我完全按照您的设置来的。

          • 雪
            9

            ipstream加进去感觉好点,可以清晰判断是Nginx还是后端返回的,防止跟开发扯皮
            "upstream": "$upstream_addr":"$upstream_status"’;

          评论已关闭!