相信很多小伙伴都見過一些商業產品中的url接口響應時間,實時匯總顯示功能。可以理解為web接口的慢查詢,與sql的慢查詢有異曲同工之妙,但是想做卻無從入手不知道怎么實現此功能,所以今天就教大家如何實現用grafana+Nginx+MySQL來實現此功能。
0x0
其實nginx本身就帶有接口響應時間的功能,只不過還需要改造下,比如說單獨記錄超過1000ms(1秒)的響應,并寫入數據庫中。要注意的是并不建議大家將記錄直接寫入數據庫中,因為數據庫有時會成為nginx的負擔,間接寫入即可。需要簡單修改下log模塊,涉及文件ngx_http_log_module.c 通常位于
nginx-1.17.9/src/http/modules/ngx_http_log_module.c
大約838行, 找到ngx_http_log_request_time函數并修改如下:
static u_char *
ngx_http_log_request_time(ngx_http_request_t *r, u_char *buf,
ngx_http_log_op_t *op)
{
ngx_time_t *tp;
ngx_msec_int_t ms;
time_t t = time(NULL);
struct tm *loc_time = localtime(&t);
tp = ngx_timeofday();
u_char slow_log[2048];
memset(slow_log, 0, sizeof(slow_log));
ms = (ngx_msec_int_t) ((tp->sec - r->start_sec) * 1000
+ (tp->msec - r->start_msec));
ms = ngx_max(ms, 0);
ngx_sprintf(slow_log, "%04d/%02d/%02d %02d:%02d:%02d %V %V?%V waste time %T.%03Mn",
loc_time->tm_year + 1900, loc_time->tm_mon + 1, loc_time->tm_mday,
loc_time->tm_hour, loc_time->tm_min, loc_time->tm_sec,
&r->headers_in.server, &r->uri, &r->args, (time_t) ms / 1000,
ms % 1000);
int logfd;
if ((logfd = open("/var/log/nginx/nginx_slow.log", O_RDWR | O_CREAT | O_AppEND,
S_IRUSR | S_IWUSR)) == -1) {
ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
"can not open file:logfilen");
}
char Server_name[256];
const char *server_name = "%.*s";
memset(Server_name, 0, sizeof(Server_name));
snprintf((char *) Server_name, sizeof(Server_name), server_name,
r->headers_in.server.len, r->headers_in.server.data);
/* 只記錄大于1秒的并且域名不是grafana.sshfortress.com */
if (ms > 1000 && strcmp("grafana.sshfortress.com", Server_name) != 0)
write(logfd, slow_log, strlen((char *)slow_log));
close(logfd);
return ngx_sprintf(buf, "%T.%03M", (time_t) ms / 1000, ms % 1000);
}
之后再編譯即可
# ./configure --prefix=/usr/local/nginx1.17.9
# make -j4 ; make install
#mkdir -p /var/log/nginx; chmod -R 777 /var/log/nginx
簡單配置下
server { listen *:80; server_name slow.sshfortress.com; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:3000; } }
啟動nginx即可,如果接口響應時間超過1秒,那么
/var/log/nginx/nginx_slow.log 中就會有記錄了。但這只是將慢查詢記錄而已,我們還需要排序以及可示化的展示。記錄也可以直接寫入mysql但我并沒有這么做,為什么不直接寫入呢,原因是如果mysql如果響應慢則會影響nginx的響應,但寫入磁盤就不會出現這種情形了。接下來就簡單實現下把數據同步寫入到數據庫中。
0x01
首先建個表 用于同步寫入記錄
CREATE TABLE `nginx_slow` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` datetime NOT NULL,
`server_name` varchar(255) NOT NULL,
`url` varchar(255) NOT NULL,
`waste_time` decimal(11,3) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
之后實現一個同步數據的工具,這里用shell即可實現,代碼如下:
#!/bin/bash
# insert_mysql.sh
set -x
if [ $# != 1 ]
then
echo "Usage insert_mysql.sh /var/log/nginx/nginx_slow.log"
exit 1
fi
tail -n 1 -f ${1}|while read var
do
value=`echo $var|awk '{print $3}'`
value2=`echo $var|awk '{print $4}'`
value3=`echo $var|awk '{print $7}'`
echo "$value $value2 $value3"
mysql -h 127.0.0.1 -usuper -pxxxxxxxxx -e "use nginx; INSERT INTO nginx_slow( date, server_name, url, waste_time) VALUES ( now(), '${value}', '${value2}', '$value3');"
done
運行腳本就可以同步寫入數據了,是不是很簡單呢
# ./insert_mysql.sh /var/log/nginx/nginx_slow.log
建議后臺運行,因為要實時同步嘛
# nohub ./insert_mysql.sh /var/log/nginx/nginx_slow.log >> /dev/null 2>&1 &
0x02
最后在grafana里面配置下當天接口慢查詢TOP 20即可,相關語句是
select n.url,avg(n.waste_time) 平均響應時長
from nginx_slow n
WHERE n.`date` > curdate()
group by 1
order by 2 desc
limit 20
或者
select n.server_name,n.url,avg(n.waste_time) 平均響應時長,count(1) 調用次數
from nginx_slow n
WHERE n.`date` > curdate()
group by 1,2
order by 3 desc
limit 50
最后效果圖如下