nginxnginx 调试 日志输出日志的几种方法

没有更多推荐了,
不良信息举报
举报内容:
nginx 开发第三方模块的时调式日志的方法(终端printf输出日志)
举报原因:
原文地址:
原因补充:
最多只允许输入30个字
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!详解用ELK来分析Nginx服务器日志的方法
转载 &发布时间:日 16:20:49 & 作者:叶剑峰
这篇文章主要介绍了用ELK来分析Nginx服务器日志的方法,ELK是三个开源软件的缩写,分别表示Elasticsearch,Logstash,Kibana,需要的朋友可以参考下
所有ELK的安装包都可以去官网下载,虽然速度稍慢,但还可以接受,官网地址:https://www.elastic.co/
在Logstash1.5.1版本,pattern的目录已经发生改变,存储在/logstash/vendor/bundle/jruby/1.9/gems/logstash-patterns-core-0.1.10/目录下,但是好在配置引用的时候是可以对patterns的目录进行配置的,所以本人在Logstash的根目录下新建了一个patterns目录。而配置目录在1.5.1版本中也不存在了,如果是rpm包安装的,可以在/etc/logstash/conf.d/下面进行配置,但个人测试多次,这样启动经常性的失败,目前还没有去分析原因(个人不推荐使用RPM包安装)。所以大家可以采用Nohup或者screen的方式进行启动
专属nginx的pattern配置:
NGINXACCESS %{IP:client} %{USER:ident} %{USER:auth} \[%{HTTPDATE:timestamp}\] \"(?:%{WORD:verb} %{NOTSPACE:request}(?: HTTP/%{NUMBER:http_version})?|-)\" %{HOST:domain} %{NUMBER:response} (?:%{NUMBER:bytes}|-) %{QS:referrer} %{QS:useragent} "(%{IP:x_forwarder_for}|-)"
由于是测试环境,我这里使用logstash读取nginx日志文件的方式来获取nginx的日志,并且仅读取了nginx的access log,对于error log没有关心。
使用的logstash版本为2.2.0,在log stash程序目录下创建conf文件夹,用于存放解析日志的配置文件,并在其中创建文件test.conf,文件内容如下:
path =& ["/var/log/nginx/access.log"]
match =& {
"message" =& "%{IPORHOST:clientip} \[%{HTTPDATE:time}\] \"%{WORD:verb} %{URIPATHPARAM:request} HTTP/%{NUMBER:httpversion}\" %{NUMBER:http_status_code} %{NUMBER:bytes} \"(?&http_referer&\S+)\" \"(?&http_user_agent&\S+)\" \"(?&http_x_forwarded_for&\S+)\""
elasticsearch {
hosts =& ["10.103.17.4:9200"]
index =& "logstash-nginx-test-%{+YYYY.MM.dd}"
workers =& 1
flush_size =& 1
idle_flush_time =& 1
template_overwrite =& true
stdout{codec =& rubydebug}
需要说明的是,filter字段中的grok部分,由于nginx的日志是格式化的,logstash解析日志的思路为通过正则表达式来匹配日志,并将字段保存到相应的变量中。logstash中使用grok插件来解析日志,grok中message部分为对应的grok语法,并不完全等价于正则表达式的语法,在其中增加了变量信息。
具体grok语法不作过多介绍,可以通过logstash的官方文档中来了解。但grok语法中的变量类型如IPORHOST并未找到具体的文档,只能通过在logstash的安装目录下通过grep -nr "IPORHOST" .来搜索具体的含义。
配置文件中的stdout部分用于打印grok解析结果的信息,在调试阶段一定要打开。
可以通过这里来验证grok表达式的语法是否正确,编写grok表达式的时候可以在这里编写和测试。
对于elasticsearch部分不做过多介绍,网上容易找到资料。
elk收集分析nginx access日志
使用redis的push和pop做队列,然后有个logstash_indexer来从队列中pop数据分析插入elasticsearch。这样做的好处是可扩展,logstash_agent只需要收集log进入队列即可,比较可能会有瓶颈的log分析使用logstash_indexer来做,而这个logstash_indexer又是可以水平扩展的,我可以在单独的机器上跑多个indexer来进行日志分析存储。
好了,现在进一步配置了。
nginx中的日志存储格式
nginx由于有get请求,也有post请求,get请求的参数是会直接显示在日志的url中的,但是post请求的参数呢,却不会在access日志中体现出来。那么我想要post的参数也进行存储纪录下来。就需要自己定义一个log格式了。
log_format logstash '$http_host $server_addr $remote_addr [$time_local] "$request" $request_body $status $body_bytes_sent "$http_referer" "$http_user_agent" $request_time $upstream_response_time';
这里的requestbody里面存放的就是POST请求的body了,然后GET请求的参数在requestbody里面存放的就是POST请求的body了,然后GET请求的参数在request里面。具体怎么分析,我们在indexer中再想。
这里的server_addr存放的是当前web机器的IP,存这个IP是为了分析日志的时候可以分析日志的原始来源。
下面是一个GET请求的例子:
api.yejianfeng.com 10.171.xx.xx 100.97.xx.xx [10/Jun/:24 +0800] "GET /api1.2/qa/getquestionlist/?limit=10&source=ios&token=&type=1&uid=304116&ver=1.2.379 HTTP/1.0" - 200 2950 "-" "TheMaster/1.2.379 (iP iOS 8.3; Scale/2.00)" 0.656 0.654
下面是一个POST请求的例子:
api.yejianfeng.com 10.171.xx.xx 100.97.xx.xx [10/Jun/:24 +0800] "POST /api1.2/user/mechanicupdate/ HTTP/1.0" start_time=&lng=110.985723&source=android&uid=328910&lat=35.039471&city= 754 "-" "-" 0.161 0.159
顺便说下,这里知识在nginx.conf中定义了一个日志格式,还要记得在具体的服务中加入日志存储。比如
server_name api.yejianfeng.
access_log /mnt/logs/api.yejianfeng.com.logstash.
log_agent的配置
这个配置就是往redis队列中塞入日志就行。output的位置设置为redis就行。
&&&&&&& file {
&&&&&&&&&&&&&&& type =& "nginx_access"
&&&&&&&&&&&&&&& path =& ["/mnt/logs/api.yejianfeng.com.logstash.log"]
&&&&&&& redis {
&&&&&&&&&&&&&&& host =& "10.173.xx.xx"
&&&&&&&&&&&&&&& port =& 8001
&&&&&&&&&&&&&&& password =& pass
&&&&&&&&&&&&&&& data_type =& "list"
&&&&&&&&&&&&&&& key =& "logstash:redis"
log_indexer的配置
log_indexer的配置就比较麻烦了,需要配置的有三个部分
input: 负责从redis中获取日志数据
filter: 负责对日志数据进行分析和结构化
output: 负责将结构化的数据存储进入elasticsearch
host =& "10.173.xx.xx"
port =& 8001
password =& pass
data_type =& "list"
key =& "logstash:redis"
其中的redis配置当然要和agent的一致了。
filter部分
解析文本可以使用grokgrok debug进行分析,参照着之前的log格式,需要一个个进行日志分析比对。这个grok语法写的还是比较复杂的,还好有在线grok比对工具可以使用。比对前面的GET和POST的日志格式,修改出来的grok语句如下:
%{IPORHOST:http_host} %{IPORHOST:server_ip} %{IPORHOST:client_ip} \[%{HTTPDATE:timestamp}\] \"%{WORD:http_verb} (?:%{PATH:baseurl}\?%{NOTSPACE:params}(?: HTTP/%{NUMBER:http_version})?|%{DATA:raw_http_request})\" (%{NOTSPACE:params})?|- %{NUMBER:http_status_code} (?:%{NUMBER:bytes_read}|-) %{QS:referrer} %{QS:agent} %{NUMBER:time_duration:float} %{NUMBER:time_backend_response:float}
这里使用了一点小技巧,params的使用,为了让GET和POST的参数都反映在一个参数上,在对应的GET和POST的参数的地方,都设计使用params这个参数进行对应。
好了,现在params中是请求的参数。比如source=ios&uid=123。但是呢,最后做统计的时候,我希望得出的是“所有source值为ios的调用”,那么就需要对参数进行结构化了。而且我们还希望如果接口中新加入了一个参数,不用修改logstash_indexer就可以直接使用,方法就是使用kv,kv能实现对一个字符串的结构进行k=v格式的拆分。其中的参数prefix可以为这个key在统计的时候增加一个前缀,include_keys可以设置有哪些key包含在其中,exclude_keys可以设置要排除哪些key。
prefix =& "params."
field_split =& "&"
source =& "params"
好了,现在还有一个问题,如果请求中有中文,那么日志中的中文是被urlencode之后存储的。我们具体分析的时候,比如有个接口是/api/search?keyword=我们,需要统计的是keyword被查询的热门顺序,那么就需要解码了。logstash牛逼的也有urldecode命令,urldecode可以设置对某个字段,也可以设置对所有字段进行解码。
urldecode {
all_fields =& true
看起来没事了,但是实际上在运行的时候,你会发现一个问题,就是存储到elasticsearch中的timestamp和请求日志中的请求时间不一样。原因是es中的请求日志使用的是日志结构存放进入es的时间,而不是timestamp的时间,这里想要吧es中的时间和请求日志中的时间统一怎么办呢?使用date命令。具体设置如下:
locale =& "en"
match =& ["timestamp" , "dd/MMM/YYYY:HH:mm:ss Z"]
具体的logstash_indexer中的全部配置如下:
match =& [
"message", "%{IPORHOST:http_host} %{IPORHOST:server_ip} %{IPORHOST:client_ip} \[%{HTTPDATE:timestamp}\] \"%{WORD:http_verb} (?:%{PATH:baseurl}\?%{NOTSPACE:params}(?: HTTP/%{NUMBER:http_version})?|%{DATA:raw_http_request})\" (%{NOTSPACE:params})?|- %{NUMBER:http_status_code} (?:%{NUMBER:bytes_read}|-) %{QS:referrer} %{QS:agent} %{NUMBER:time_duration:float} %{NUMBER:time_backend_response:float}"
prefix =& "params."
field_split =& "&"
source =& "params"
urldecode {
all_fields =& true
locale =& "en"
match =& ["timestamp" , "dd/MMM/YYYY:HH:mm:ss Z"]
output部分
这里就是很简单往es中发送数据
elasticsearch {
embedded =& false
protocol =& "http"
host =& "localhost"
port =& "9200"
user =& "yejianfeng"
password =& "yejianfeng"
这里有个user和password,其实elasticsearch加上shield就可以强制使用用户名密码登录了。这里的output就是配置这个使用的。
查询elasticsearch
比如上面的例子,我要查询某段时间的params.source(其实是source参数,但是前面的params是前缀)调用情况
$url = 'http://xx.xx.xx.xx:9200/logstash-*/_search';
$filter = '
"query": {
"range" : {
"@timestamp" : {
"aggs" : {
"group_by_source" : {"terms" : {"field" : "params.source"}}
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具nginx&日志和监控
原文地址:&
Logging and Monitoring日志和监控
This section describes how to configure logging of errors and
processed requests, as well as how to use the runtime monitoring
service of NGINX and NGINX Plus.
本文学习,如何配置错误日志与处理请求,以及如何使用NGINX和NGINX+的实时监控服务。
In This Section &本章有
& 搭建错误日志
& 搭建访问日志
& & 记录到系统日志
& &实时活动监控
Setting Up the Error Log搭建错误日志
NGINX writes information about encountered issues of different
severity levels to the error log. The&directive
sets up logging to a partifular file, stderr, or syslog and
specifies the minimal severity level of messages to log. By
default, the error log is located at&&logs/error.log&(the
absolute path depends on the operating system and installation),
and messages from all severity levels above the one specified are
Nginx把遇到的不同级别的问题信息写到错误日志。&指令配置记录到特定的文件,stderr,或者syslog,配置写到日志的最低级别信息。默认地,错误日志位于logs/error.log(绝对路径取决于操作系统和安装方式),比指定级别更高级别的信息都将被记录。
The configuration below changes the minimal severity level of error
messages to log from&error&to&&warn&.
下面这个配置把记录到日志的错误信息的最低级别由 error 改为 warn。
error_log logs/error.
In this case messages of&warn&,&&error&,&&crit&,&&alert&,
and&&emerg&levels
will be logged.
这样warn, error, crit, alert, emger 级别的信息都会被记录。
The default setting of the error log works globally. To override
it, the&error_log&directive
should be placed in the&main&context.
The settings of the&&main&context
are always inherited by other levels.
The&&error_log&directive
can be specified on other levels too, cancelling the effect
inherited from the higher levels. In case of an error, the message
will be written to only one error log. This log will be the closest
to the level where the error has occurred. However, if
several&&error_log&directives
are specified on the same level, the message will be written to to
all logs specified.
默认的错误日志设置是全局的。要覆盖它,error_log
指令必须放在main环境中。man环境里的设置都会被其他层继承。error_log指令也可以在其他层里指定,以取消从更高层继承下来的。如果发生一
个错误,信息只会被写到一个错误日志。这个日志将写到错误发生的最近的那一层。然而,如果在同一个层定义了多个error_log指令,信息会被写到所有
指定的日志文件。
Note: Using several error log directives at the same level are
supported in NGINX versions 1.5.2 and greater.
注意:同一层使用多个错误日志需要Nginx版本为1.5.2或更高。
Setting Up the Access Log设置访问日志
To the access a log, NGINX writes information about client requests
after the request is processed. By default, the access log is
located at&logs/access.log&,
and the information is written to the log in the predefined,
combined format. To override the default setting, use
the&&directive
to configure a format of logged messages, as well as
the&&directive
to specify the location of the log and the format. The format is
defined using variables.
Nginx处理请求后把关于客户端请求的信息写到访问日志。默认,访问日志位于
logs/access.log,写到日志的信息是预定义的、组合的格式。要覆盖默认的配置,使用&指令来配置一个记录信息的格式,同样使用指令到设置日志和格式和位置。格式定义使用变量。
The following examples define a format that extends the standard
combined format with the value indicating the ratio of gzip
compression of the response. The format is then applied to a
virtual server that enables compression.
下面这个例子定义一个格式,这个格式在标准组合格式上进行扩展加入对响应进行gzip压缩的比率的值。该格式被应用于一个开启了压缩的虚拟服务器。
log_format compression '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" "$gzip_ratio"';
access_log /spool/logs/nginx-access.log
Logging can be optimized by enabling the buffer for log messages
and the cache of descriptors of frequently used log files whose
names contain variables. To enable buffering use the&buffer&parameter
of the&&directive
to specify the size of the buffer. The buffered messages are then
written to the log file when the next log message does not fit into
the buffer as well as in some other&&.
To enable caching of log file descriptors, use
the&directive.
开启日志信息缓冲,被频繁使用且名字包含变量的文件的操作的缓存,能够优化日志记录。要开始缓冲,使用指令的buffer参数来指定缓冲的大小。缓冲区里的信息在缓冲区不够写下一个信息时以及另外的一些&下写入日志文件。要开启文件操作的缓存,使用&指令。
Similar to the&error_log&directive,
the&&access_log&directive
defined on a level overrides the settings from the previous levels.
When processing of a request is completed, the message is written
to the log that is configured on the current level, or inherited
from the previous levels. If one level defines multiple access
logs, the message is written to all of them.
与error_log指令相似,
定义了access_log指令的层将会把从上一层继承下来的设置覆盖。当一个请求的处理完毕,信息被写到由当前层定义或者从上层继承下来的日志文件中。如果一个层里定义了多个访问日志,信息会被写到所有日志中。
Enabling Conditional Logging开启有条件的日志记录
Conditional logging allows excluding trivial or non-important log
entries from the access log. In NGINX, conditional logging is
enabled by the&if&parameter
of the&&directive.
根据条件的日志记录能不记录细枝末节和不重要的日志条目到访问日志中。在Nginx中,条件性日志记录使用指令的
if 参数开启。
For example, it makes possible to exclude requests with HTTP status
codes 2XX (Success) and 3XX (Redirection):
例如,可以把状态码以2和3开头的HTTP请求忽略不计:
map $status $loggable {
default 1;
access_log /path/to/access.log combined if=$loggable;
Logging to Syslog记录到系统日志
Syslog is a standard for computer message logging and allows
collecting log messages from different devices on a single syslog
server. In NGINX, logging to syslog is configured with
the&syslog:&prefix
in&&and&&directives.
系统日志是一个计算机信息记录标准,能够记录来自不同设备的日志信息到一个单一的系统日志服务器。在Nginx中,记录到系统日志要在&和&&指令中加前缀
syslog: 来配置。
Syslog messages can be sent to a&server=&which
can be a domain name, an IP address, or a UNIX-domain socket path.
A domain name or IP address can be specified with a port, by
default port 514 is used. A UNIX-domain socket path can be
specified after the&&unix:&prefix:
系统日志信息能被发送到一个server=,server=后面可以是一个域名,一个IP地址或者一个unix-domain套接字路径。域名或者ip地址能指定端口,默认端口为514,unix-domain套接字路径跟在前缀unix:后:
error_log server=unix:/var/log/nginx.
access_log syslog:server=[2001:db8::1]:1234,facility=local7,tag=nginx,severity=
In the example, NGINX error log messages will be written to UNIX
domain socket with the&debug&logging
level, and the access log will be written to a syslog server with
IPv6 address and port 1234.
本例中,Nginx错误日志消息以debug日志级别记录到 UNIX
域套接字,访问日志将被记录到一个IPv6地址商品为1234的系统日志服务器。
The&facility=&parameter
specifies the type of program which is logging the message. The
default value is&&local7&.
Other values may be:&&auth&,&&authpriv&,&&daemon&,&&cron&,&&ftp&,&&lpr&,&&kern&,&&mail&,&news&,&&syslog&,&&user&,&&uucp&,&local0
… local7&.
参数&facility=&指定记录日志消息的程序类型。缺省值为local7,其他可用值有:&&auth&,&&authpriv&,&&daemon&,&&cron&,&ftp&,&&lpr&,&&kern&,&&mail&,&news&,&&syslog&,&&user&,&&uucp&,&&local0
… local7&.
The&tag=&parameter
will apply a custom tag to syslog messages, in our example the tag
is&&nginx&.
参数&tag=&在系统日志消息中应用一个自定义标签,上例中标签为nginx。
The&severity=&parameter
sets the&severity&level of syslog
messages for access log. Possible values in order of increasing
severity are:&&debug&,&&info&,&&notice&,&&warn&,&&error&(default),&&crit&,&&alert&,
and&&emerg&.
In our example, the severity level&&error&will
also enable&&crit&,&&alert&,
and&&emerg&levels
to be logged.
参数&severity=&设置访问日志的系统日志消息的严重级别。可使用的值按严重级别顺序递增为:&debug&,&&info&,&notice&,&&warn&,&&error&(default),&&crit&,&&alert&,
and&&emerg。&我们的例子中,严重级别error将开启crit,
alert, emerg 级别的记录。
Live Activity Monitoring实时活动监控
NGINX Plus provides a real-time activity monitoring interface that
shows key load and performance metrics of your upstream servers as
well as other data including:
Nginx + 提供一个实时活动监控界面,展示键的负载和上游服务器的性能指标,以及其他数据包括:
NIGNX basic version, uptime and identi
Nginx基础版本,运行时间和认证信息;
total and current numbers of conn
连接和请求的当前数目以及总数目;
request and response counts for each&&;
每个&的请求和响应数;
request and response counts per server in
servers, plus health-check a
每个服务器动态配置组的请求和响应数,还有健康检测和正常运行时间统计;
statistics per server, including its current state and total values
(total fails etc.)
统计每个服务器,包含当前状态和总体值(总体失败次数等)。
instrumentation for each named&&.
每个命名过的缓存空间的检测表。
The complete list of metrics is available&.
性能指标的完整列表&。
The statistics can be viewed from the&status.html&page
already included in each NGINX Plus package. The page polls status
information and displays it in a simple table:
统计数据可以从status.html页面查看,该页面已包含在每个Nginx+的包里。页面统计状态信息并且展示在一个简单的表里:&
And using a simple RESTful JSON interface, it’s easy to connect
these stats to live dashboards and third-party monitoring
还可以使用一个简单的 RESTful JSON 接口,可以通过第三方监控平台轻松连接这些状态做一个实时仪表盘。
Enabling Activity Monitoring开启活动监控
To enable real-time activity monitoring and the JSON interface, you
must specify the location that checks the exact match of the URI
with&/status&and
contains the&&directive.
To enable the&&status.html&page,
you must specify one more location that sets it:
要开启实时活动监控和 JSON 接口,必须在精确匹配 /status 的 location 里包含&指令。要启用status.html页面,你必须在至少一个location里设置它:
listen 127.0.0.1;
root /usr/share/nginx/
location /status {
location = /status.html {
the following configuration, the
webpage&&status.html&located
at&&/usr/share/nginx/html
can be requested by the URL&
http://127.0.0.1/status.html
根据这个配置,网页status.html位于/usr/share/nginx/html能通过URL
http://127.0.0.1/status.html 访问到。
Using RESTful JSON Interface
RESTful JSON 接口
NGINX Plus stats can be easlily connected to third-party
applications, such as performance dashboards. This can be done with
the JSON interface.
Nginx+的统计能轻松连接到第三方应用,比如性能仪表盘。可以通过JSON接口实现。
If you request&/status&(or
whichever URI matches the location group), then NGINX Plus will
respond with a JSON document containing the current activity
如果你请求/status(或者任何一个能匹配这个location
组的URI),Nginx+将响应一个包含当前活动数据的JSON文档。
The status information of any element in the JSON document can be
requested by a slash-separated URL:
JSON文档的每一个元素的状态信息都可以通过在请求后用斜线分隔的URL来请求:
http://127.0.0.1/status
http://127.0.0.1/status/nginx_version
http://127.0.0.1/status/caches/cache_backend
http://127.0.0.1/status/upstreams
http://127.0.0.1/status/upstreams/backend
http://127.0.0.1/status/upstreams/backend/1
http://127.0.0.1/status/upstreams/backend/1/weight
To learn more about NGINX Plus, please see the descriptions of
相关文章推荐:
本文来自:
本文链接:
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。没有更多推荐了,
不良信息举报
举报内容:
Nginx 开启 debug 日志的办法
举报原因:
原文地址:
原因补充:
最多只允许输入30个字
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!

我要回帖

更多关于 nginx rewrite 调试 的文章

 

随机推荐