介绍
以前我们为nginx做统计,都是通过对日志的分析来完成.比较麻烦,现在基于ngx_lua插件,开发了实时统计站点状态的脚本,解放生产力.
项目主页: https://github.com/skyeydemon/ngx-lua-stats
功能
- 支持分不同虚拟主机统计, 同一个虚拟主机下可以分不同的location统计.
- 可以统计与query-times request-time status-code speed 相关的数据.
环境依赖
- nginx + ngx_http_lua_module
安装
http://wiki.nginx.org/HttpLuaModule#Installation
使用方法
添加全局字典
在nginx的配置中添加dict的初始化, 类似如下
lua_shared_dict log_dict 20M;
lua_shared_dict result_dict 20M;
lua_shared_dict result_dict 20M;
1
2
|
lua_shared_dict log_dict20M;
lua_shared_dict result_dict20M;
|
为特定的location添加统计
只需要添加一句即可~~
将lua脚本嵌套进nginx的配置中, 例如:
server {
listen 8080;
server_name weatherapi.market.xiaomi.com;
access_log /home/work/nginx/logs/weatherapi.market.xiaomi.com.log milog;
location / {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://weatherapi.market.xiaomi.com_backend;
listen 8080;
server_name weatherapi.market.xiaomi.com;
access_log /home/work/nginx/logs/weatherapi.market.xiaomi.com.log milog;
location / {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://weatherapi.market.xiaomi.com_backend;
log_by_lua_file ./site-enable/record.lua;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
|
server{
listen8080;
server_name weatherapi.market.xiaomi.com;
access_log/home/work/nginx/logs/weatherapi.market.xiaomi.com.log milog;
location/{
proxy_set_header Host$host;
proxy_set_headerX-Forwarded-For$remote_addr;
proxy_pass http://weatherapi.market.xiaomi.com_backend;
log_by_lua_file./site-enable/record.lua;
}
}
|
输出结果
通过配置一个server, 使得可以通过curl获取到字典里的所有结果
server {
listen 8080 default;
server_name _;
location / {
return 404;
}
listen 8080 default;
server_name _;
location / {
return 404;
}
location /status {
content_by_lua_file ./site-enable/output.lua;
}
location /empty_dict {
content_by_lua_file ./site-enable/empty_dict.lua;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
server{
listen8080default;
server_name_;
location/{
return404;
}
location/status{
content_by_lua_file./site-enable/output.lua;
}
location/empty_dict{
content_by_lua_file./site-enable/empty_dict.lua;
}
}
|
可以通过如下命令获取
curl ip_addr:8080/status
清理字典
运行一段时间之后, 字典会变大. 可以通过如下接口清理
curl ip_addr:8080/empty_dict