Skip to content

Nginx Parser

Sun Jianbo edited this page Jun 7, 2018 · 10 revisions

Nginx Parser 是专门解析Nginx日志的解析器。仅需指定nginx的配置文件地址,即可进行nginx日志解析。

Nginx Parser的解析原理

Nginx Parser 会根据Nginx配置文件去寻找Nginx日志的生成格式,举例来说:

 log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $bytes_sent $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for" ' '$upstream_addr $host $sent_http_x_reqid $request_time'; 

这个日志格式会生成一个正则表达式,匹配每个$符号后的字符串,以格式中定义的分隔符为正则表达式的终结符。 如 $remote_addr 后面跟着空格,则认为匹配的remote_addr 字段,匹配到空格为止。 如果被双引号""包裹,如"$http_user_agent",则认为匹配到双引号为止,又比如[$time_local]会认为匹配左括号[开始到右括号]结尾。

通过上述生成的正则表达式,就可以匹配 Nginx access日志了。

上述方式生成的正则表达式可以解析大部分情况下的Nginx配置,但是确实也存在一些情况会出现解析异常,如上述的case下,如果http_user_agent没有通过双引号引起来,那么就会导致提前匹配到http_user_agent中可能存在的空格,导致解析失败。针对这样的情况,我们就推荐使用Grok Parser来解析

典型配置如下

 "parser":{	"name":"nginx_parser", "type":"nginx", "nginx_log_format_path":"/opt/nginx/conf/nginx.conf", "nginx_log_format_name":"main", "nginx_schema":"time_local date,bytes_sent long,request_time float,body_bytes_sent long", "labels":"machine xxx123, team pandora" }, 
  • Nginx Parser是根据您Nginx配置文件自动生成配置正则表达式解析日志的方式,字段名称和Nginx配置文件中 log_format定义的名称一致。

  • nginx_log_format_path 填写nginx配置文件,配置文件中需要包含 log_format格式,如图1.

  • nginx_log_format_name 实际access log使用的格式名称,如图2

  • nginx_schema 默认情况下nginx日志都被解析为string,指定该格式可以设置为float、long、date等三种类型。指定范式为逗号分隔每个字段和类型,每个字段和类型用空格分隔,左边为字段名称,右边为类型。

  • nginx_log_format_regex 若根据配置文件自动生成的正则表达式无效,可通过此配置手动填写

  • labels中定义的标签如果跟数据有冲突,labels中的标签会被舍弃

  • disable_record_errdata 默认为false,解析失败的数据会默认出现在"pandora_stash"字段,该选项可以禁止记录解析失败的数据。

  • 图1 http://op26gaeek.bkt.clouddn.com/logformat.png

图1

Nginx Parser时完整的logkit配置

{ "name":"nginx_runner", "reader":{ "mode":"file", "meta_path":"meta",	"log_path":"/opt/nginx_logs/logs/access.log" }, "parser":{	"name":"nginx_parser", "type":"nginx", "nginx_log_format_path":"/opt/nginx/conf/nginx.conf", "nginx_log_format_name":"main", "nginx_schema":"time_local date,bytes_sent long,request_time float,body_bytes_sent long" }, "senders":[{ "name":"pandora_sender", "sender_type":"pandora", "pandora_ak":"your_ak", "pandora_sk":"your_sk", "pandora_host":"https://pipeline.qiniu.com", "pandora_repo_name":"my_nginx_log", "pandora_region":"nb",	"pandora_schema_free":"true", "pandora_gzip": "true", "pandora_enable_logdb":"true",	"fault_tolerant":"true", "ft_save_log_path":"./ft_log", "ft_strategy":"always_save", "ft_procs":"2" }] } 
Clone this wiki locally