一般来说,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);
这样当接口出现问题的时候,可以方便的查看当时的请求内容和响应内容,更容易的查找问题,最后附上查看日志截图!