如何将Nginx日志改成JSON格式

发布时间:2021-08-21 10:17:11 作者:小新
来源:亿速云 阅读:168

这篇文章将为大家详细讲解有关如何将Nginx日志改成JSON格式,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

Nginx 日志默认为普通文本的格式,例如,下面是 Nginx 的一行访问日志:

10.88.122.105 - - [02/Dec/2017:09:15:04 +0800] "GET /js/pagination.js HTTP/1.1" 304 0 "http://10.88.105.20:8063/stockrecommand.html" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)" "-" 0.000

为了便于利用 Elastic Stack 日志平台收集展示 Nginx 的日志,可以将 Nginx 的日志改成 json 的格式。修改后的 json 日志格式如下所示:

{ "@timestamp": "12/Dec/2017:14:30:40 +0800", "remote_addr": "10.88.122.108", "referer": "-", "request": "GET / HTTP/1.1", "status": 304, "bytes":0, "agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36", "x_forwarded": "-", "up_addr": "-","up_host": "-","up_resp_time": "-","request_time": "0.000" }

为了修改 Nginx 的日志格式改成 json,需要修改 Nginx 的配置文件,笔者 Nginx 的配置文件为 /usr/local/nginx/conf/nginx.conf。

http {
  include    mime.types;
  default_type application/octet-stream;
  charset utf-8;
  log_format main '$remote_addr - $remote_user [$time_local] "$request" '
           '$status $body_bytes_sent "$http_referer" '
           '"$http_user_agent" "$http_x_forwarded_for" $request_time';
  log_format log_json '{ "@timestamp": "$time_local", '
'"remote_addr": "$remote_addr", '
'"referer": "$http_referer", '
'"request": "$request", '
'"status": $status, '
'"bytes": $body_bytes_sent, '
'"agent": "$http_user_agent", '
'"x_forwarded": "$http_x_forwarded_for", '
'"up_addr": "$upstream_addr",'
'"up_host": "$upstream_http_host",'
'"up_resp_time": "$upstream_response_time",'
'"request_time": "$request_time"'
' }';
  access_log logs/access.log log_json;
  (省略内容)
}

在 Nginx 的配置文件nginx.conf中,我们定义了两种的日志格式:main和log_json,其中,main为普通的文本格式,log_json为 json 格式。log_json其实就是手工构造一个 json 字符串。定义了 json 的日志格式后,便可以指定 access log 为 json 格式:

access_log logs/access.log log_json;

修改 Nginx 的配置,重启 Nginx ,便可以看到 json 格式的日志,重启 Nginx:

nginx -s reload

关于“如何将Nginx日志改成JSON格式”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. Nginx学习笔记(2)------Nginx日志
  2. nginx 日志

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

nginx json

上一篇:WDCP如何安装使用

下一篇:Kloxo-MR如何安装使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》