nginx日志记录请求和响应数据

来源:互联网 发布:个人简介网页制作源码 编辑:程序博客网 时间:2024/06/05 01:20

一、安装nginx

    安装nginx教程就不具体介绍了,网上教程很多,随便搜几个就ok。

二、安装openresty

    推荐安装openresty。openresty是一个打包程序,包含大量的第三方Nginx模块,包括lua。咱们现在主要是使用其中的ngx_lua模块来帮助nginx日志记录response。

1、安装openresty依赖ubuntu安装:    # sudo apt-get install libreadline-dev libncurses5-dev libpcre3-dev \    libssl-dev perl make build-essentialcentos安装:    # yum install readline-devel pcre-devel openssl-devel gcc2、下载openresty源码:# wget http://openresty.org/download/openresty-1.9.7.4.tar.gz3、解压# tar xf openresty-1.9.7.4.tar.gz4、编译安装# cdopenresty-1.9.7.4# ./configure --prefix=/opt/openresty \              --with-luajit \              --without-http_redis2_module \              --with-http_iconv_module# make && make install

此方法本次测试暂时不可用,请参考官方安装文档:http://openresty.org/cn/linux-packages.html

5、运行测试

-- 1. 修改配置文件如下:$ cat /opt/openresty/nginx/conf/nginx.confworker_processes  1;error_log logs/error.log info;events {    worker_connections 1024;}http {    server {        listen 8003;        location / {            content_by_lua 'ngx.say("hello world.")';        }    }}-- 2. 启动nginx$ /opt/openresty/nginx/sbin/nginx-- 3. 检查nginx$ curl http://127.0.0.1:8003/hello world.

三、配置nginx.conf

worker_processes  1;error_log logs/error.log info;events {    worker_connections 1024;}http {    log_format main '$remote_addr | $remote_user | [$time_local] | '        '"$request" | $status | $body_bytes_sent | '        '"$http_referer" | "$http_user_agent" | $request_time | '        '"$request_body" | "$resp_body"';    access_log  logs/access.log  main;    upstream bankend {        server 192.168.136.102:9090;        server 192.168.136.103:9090;    }    server {        listen       8000;        server_name  localhost;        set $resp_body "";        location / {    proxy_pass http://bankend;                lua_need_request_body on;            body_filter_by_lua '                local resp_body = string.sub(ngx.arg[1], 1, 1000)                ngx.ctx.buffered = (ngx.ctx.buffered or "") .. resp_body                if ngx.arg[2] then                    ngx.var.resp_body = ngx.ctx.buffered                end            ';        }    }}

四、运行

    启动nginx后,发送请求,nginx的日志这个时候已经可以正常记录请求和相应数据了。