nginx打印请求头日志方法亲测可用(openresty)

一、前言

之前想用nginx打印收到的请求的请求头,但是只找到打印请求体的,没有打印请求头的,感觉原版nginx不支持。

建议如果想打印请求头,先换成openresty

(本人安装的是openresty-1.21.4.1.tar.gz版本的)

网上有些文章的配置,本人试了后发现不行,各种报错,不知道为什么;

这个的配置可以,在此记录下

二、openresty打印请求头方法

1.安装好openresty

2.找到nginx配置文件nginx.conf,增加一种日志打印格式,可以写在http { 里:


http {
    include       mime.types;
    default_type  application/octet-stream;

    #这个是默认日志格式
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    #这个是自定义的打印请求头的日志格式
        log_format accesslog_headers  '$time_iso8601'
                        '\t$request_time'
                        '\t$status'
                        '\t$remote_addr'
                        '\t$http_x_forwarded_for'
                        '\t$host'
                        '\t$server_addr'
                        '\t$request_method'
                        '\t$uri' #cs-uri-stem
                        '\t$args' #cs-uri-query
                        '\t"$http_user_agent"'
                        '\t"$http_referer"'
                        '\t$bytes_sent'
                        '\t$request_length'
                        '\t$upstream_addr'
                        '\t$upstream_status'
                        '\t$upstream_response_time'
                        '\t$request_uri'
                        '\t$request_headers'; #设置这个变量,后面赋值

    #这里配置后全局的日志都会用默认日志格式main,日志打印位置是logs文件夹里的access.log文件
    access_log  logs/access.log  main;


3.继续修改nginx.conf,可以在想打印request_header的location里加,也可以加在全局。

以下是在某个location里加的方法样例:

location /my/header/api/ {
        #这个是增加的,使用打印请求头的日志格式accesslog_headers,日志打印位置是logs/access_headers.log
        access_log  logs/access_headers.log  accesslog_headers;
        
        #给request_headers变量赋值,使用lua获取到请求头
        set_by_lua $request_headers 'local h = ngx.req.get_headers()
                                local request_headers_all = ""
                                for k, v in pairs(h) do
                                    request_headers_all = request_headers_all .. ""..k..": "..v..";"
                                end
                                return request_headers_all';

这样配置可以指定访问某个location才打印header,并且不影响main格式的日志,比较方便。

4.保存配置文件,重启nginx。

5.当有请求访问/my/header/api/时,就会打印日志,本人的日志文件路径在/home/myuser/openresty/nginx/logs /access_headers.log

三、备注

1.如果想打印请求体,直接日志格式log_format里加默认的$request_body即可(不用自己赋值),然后就会打印出来。(再次注意原版nginx没有$request_header,所以才换成openresty自己用lua赋值)

2.如果想打印响应头和响应体(例如后台服务器返回的),也可以自己日志格式里加2个变量,后续用lua赋值,然后打印。

猜你喜欢

转载自blog.csdn.net/BHSZZY/article/details/130614624