分享

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

 WindySky 2019-02-28

一、安装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-essential

centos安装:

    # yum install readline-devel pcre-devel openssl-devel gcc

2、下载openresty源码:

# wget http:///download/openresty-1.9.7.4.tar.gz

3、解压

# tar xf openresty-1.9.7.4.tar.gz

4、编译安装

# cdopenresty-1.9.7.4

# ./configure --prefix=/opt/openresty \

              --with-luajit \

              --without-http_redis2_module \

              --with-http_iconv_module

# make && make install

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

5、运行测试

-- 1. 修改配置文件如下:

$ cat /opt/openresty/nginx/conf/nginx.conf

worker_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的日志这个时候已经可以正常记录请求和相应数据了。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多