openrestry 响应慢的请求_利用openresty来记录请求响应日志–方便调试程序

一般来说,nginx的日志只能记录请求相关信息和响应时间,要想将响应信息记录下来,只能在程序中扩展功能,而这次,我们通过openresty来记录响应内容,这样的好处是不影响业务功能,又增加了日志,方便查看问题!

首先在nginx.conf中配置如下关键信息

log_format log2 '$remote_addr - - $time_local - - $request_method - - $request_uri - - $status - - $request_time - - "$request_body" - - "$resp_body"';

log_escape_non_ascii off;

日志分别记录的是

请求IP

请求时间

请求方法

请求url

响应状态吗

执行时间

post内容

响应内容

然后在需要配置日志的server中配置如下关键信息

set $resp_body "";

lua_need_request_body on;

body_filter_by_lua_file lua/log_by.lua;

access_log /usr/local/openresty/test/logs/access_test.log log2;

log_by.lua文件内容如下

local chunk, eof = ngx.arg[1], ngx.arg[2]

local buffered = ngx.ctx.buffered

if not buffered then

buffered = {}

ngx.ctx.buffered = buffered

end

if chunk ~= "" then

buffered[#buffered + 1] = chunk

ngx.arg[1] = nil

end

if eof then

local whole = table.concat(buffered)

ngx.ctx.buffered = nil

ngx.arg[1] = whole

ngx.var.resp_body = ngx.arg[1]

end

一般,这样的情况下,记录日志的功能就配置好了,但由于我们的后端是PHP,接口输出的json中文会乱码显示,非常的不方便!因此我们又简单写了个分析日志工具来更方便的查看日志,PHP代码如下:

#!/usr/bin/php

error_reporting(0);

function encode_json($str) {

return urldecode(json_encode(url_encode($str)));

}

function url_encode($str) {

if(is_array($str)) {

foreach($str as $key=>$value) {

$str[urlencode($key)] = url_encode($value);

}

} else {

$str = urlencode($str);

}

return $str;

}

$need_list = array("\\x22","\\x0A","\\x09","\\x5Cu");

$replace_list = array('"',"\n","\t","\u");

$handle = popen("tail -f /usr/local/openresty/test/logs/access_test.log 2>&1", 'r');

while(!feof($handle)) {

$line_str = fgets($handle);

$line_arr = explode("- -", $line_str);

echo trim($line_arr[0])."\r\n";

echo trim($line_arr[1])."\r\n";

echo trim($line_arr[2])."\r\n";

echo trim($line_arr[3])."\r\n";

echo trim($line_arr[4])."\r\n";

echo trim($line_arr[5])."\r\n";

$request = trim($line_arr[6]);

$request = str_replace($need_list,$replace_list,$request);

echo urldecode($request)."\r\n";

$res = trim($line_arr[7]);

$res = str_replace($need_list,$replace_list,$res);

$res = trim($res,'"');

echo encode_json(json_decode($res,true))."\r\n\r\n";

}

pclose($handle);

这样当接口出现问题的时候,可以方便的查看当时的请求内容和响应内容,更容易的查找问题,最后附上查看日志截图!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值