OpenResty中 将响应内容写入到日志中

文章介绍了如何在Nginx中使用ngx.log()函数将HTTP响应内容记录到error.log,以及如何通过自定义log_format和lua模块将响应内容写入access.log,包括配置log_format,启用lua_need_request_body,定义body_filter_by_lua块,并在location中设置access_log。
摘要由CSDN通过智能技术生成

入职小白
今天带我的大哥给了我一个任务
将服务器的http响应内容记录在日志中!!!

经过一系列的网上查找
可以使用ngx.log()

ngx.log()会将日子写到error.log文件中
所以首先要在配置文件中开error_log 命令
还有设置对应的log等级
具体如下:
error_log  logs/error.log  debug;

但是,ngx.log()函数只能将日志写入到error.log中,且格式固定,不能随意加入其他变量。
如下:

ngx.log(ngx.INFO, '请求方法:', ngx.var.request_method)
ngx.INFO为等级,后面的为日志内容。

最后记录的内容如下:

2023/07/07 21:11:01 [info] 2536#12044: *194 [lua] getHeader.lua:11: 请求方法:GET, client: 127.0.0.1, server: localhost, request: "GET /lua/getHeader?a=1&b=2&c=3 HTTP/1.1", host: "localhost:9000"

其中,加入的内容是

请求方法:GET, 

其他的是不能动的
所以要使用这个方法将响应内容写到日子中,是相当麻烦的。

简单来说,就是

每写一行ngx.say(......)
后面就需要加入一行ngx.lon(ngx.INFO, ......)

这显然不可以这样干啊 太费劲了 大哥既然给了问题 肯定不是靠这样的笨办法实现的。

于是又开始在网上耕耘,经过不懈努力
最后找到了这样一段代码
可以将http响应内容写入到access.log

其中以下内容为log格式定义

log_format 	mylog escape=json '{ "timestamp": "$time_iso8601", '
                     '"remote_addr": "$remote_addr", '
                     '"body_bytes_sent": $body_bytes_sent, '
                     '"request_time": $request_time, '
                     '"response_status": $status, '
                     '"request": "$request", '
                     '"request_method": "$request_method", '
                     '"host": "$host",'
                     '"request_body":"$request_body",'
                     '"response_body":"$resp_body",'
                     '"upstream_cache_status": "$upstream_cache_status",'
                     '"upstream_addr": "$upstream_addr",'
                     '"http_x_forwarded_for": "$http_x_forwarded_for",'
                     '"http_referrer": "$http_referer", '
                     '"http_user_agent": "$http_user_agent" }';
'"response_body":"$resp_body",'  为对应的响应内容

修改完成保存,会报错,说’$resp_body没有定义
所以还要再下面加上这样一段代码:

		lua_need_request_body on;
		set $resp_body "";
		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
		';

同时,还需要在对应的location内开启日志 access_log logs/access.log mylog;。

		location ~ /lua/(.+) {
			access_log  logs/access.log  mylog;
			default_type text/html;
			charset utf8;
			content_by_lua_file lua/$1.lua;
		}

整体配置文件如下:

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 	mylog escape=json '{ "timestamp": "$time_iso8601", '
                     '"remote_addr": "$remote_addr", '
                     '"body_bytes_sent": $body_bytes_sent, '
                     '"request_time": $request_time, '
                     '"response_status": $status, '
                     '"request": "$request", '
                     '"request_method": "$request_method", '
                     '"host": "$host",'
                     '"request_body":"$request_body",'
                     '"response_body":"$resp_body",'
                     '"upstream_cache_status": "$upstream_cache_status",'
                     '"upstream_addr": "$upstream_addr",'
                     '"http_x_forwarded_for": "$http_x_forwarded_for",'
                     '"http_referrer": "$http_referer", '
                     '"http_user_agent": "$http_user_agent" }';
					 
    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       9000;
        server_name  localhost;
		resolver 	 8.8.8.8;
		
		lua_need_request_body on;
		set $resp_body "";
		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
		';
		
        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        #location / {
        #    root   html;
        #    index  index.html index.htm;
        #}
		
		lua_code_cache off;
		location ~ /lua/(.+) {
			access_log  logs/access.log  mylog;
			default_type text/html;
			charset utf8;
			content_by_lua_file lua/$1.lua;
		}
		

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
OpenResty使用Redis的过程是通过Lua脚本来实现的。首先,需要进行准备工作,确保OpenResty和Redis环境的配置正确。OpenResty主要用于解决高并发问题,而为了避免数据库成为高并发的瓶颈,操作Redis变得不可避免。 如果对OpenResty不太了解,可以参考相关文章进行学习。在Windows系统下,可以使用ZeroBrane Studio进行开发和调试OpenResty代码。 在使用OpenResty操作Redis之前,需要将相关的代码添加到配置文件。具体的配置数据可以根据自己的Redis数据库情况进行修改。配置文件包含了连接信息、超时时间以及Redis的库等信息。 在使用OpenResty时,可以根据具体的需求和场景,编写Lua脚本来操作Redis,实现数据的读取、写入和删除等操作。通过调用相关的Redis命令,可以实现与Redis的交互。 总结来说,OpenResty使用Redis的过程是通过Lua脚本与Redis进行交互,通过配置文件设置Redis的连接信息和相关参数,然后根据需求编写Lua脚本来操作Redis的数据。这样可以有效地解决高并发问题并提升系统性能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [OpenResty高并发最佳实践--Redis操作](https://blog.csdn.net/lupengfei1009/article/details/86160652)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值