Skip to content

Instantly share code, notes, and snippets.

@emacsist
Created May 31, 2018 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emacsist/312fd84abc2e704040a78ba210fc5c6d to your computer and use it in GitHub Desktop.
Save emacsist/312fd84abc2e704040a78ba210fc5c6d to your computer and use it in GitHub Desktop.
-- 全局字典
local access = ngx.shared.access
-- Nginx中的 host 主机
local host = "host"
-- 响应的状态码
local status = ngx.var.status
-- 客户端发送的字节数
local body_bytes_sent = ngx.var.body_bytes_sent
-- 客户端请求的时间
local request_time = ngx.var.request_time
-- 负载均衡响应时间
local upstream_response_time = ngx.var.upstream_response_time
-- 以秒为单位的时间 timestamp
local timestamp = os.date("%s")
-- 只保留最近70秒的数据
local expire_time = 70
-- 客户端请求的内容
local request_body = ngx.var.request_body
-- 客户端请求的URL
-------------------------------------------------------------------------------
-- 总请求数统计
local total_req_key = table.concat({host,"-total_req-",timestamp})
local total_req_sum = access:get(total_req_key) or 0
total_req_sum = total_req_sum + 1
access:set(total_req_key, total_req_sum, expire_time)
-- 根据状态码不同的统计
local status_key = table.concat({host,"-",status,"-",timestamp})
local status_sum = access:get(status_key) or 0
status_sum = status_sum + 1
access:set(status_key, status_sum, expire_time)
-- 非成功的请求统计
local status_fail_key = table.concat({host,"-","error","-",timestamp})
if (status ~= "204" and status ~= "200")
then
local status_fail_sum = access:get(status_fail_key) or 0
status_fail_sum = status_fail_sum + 1
access:set(status_fail_key, status_fail_sum, expire_time)
end
-- 流量统计
local flow_key = table.concat({host,"-flow-",timestamp})
local flow_sum = access:get(flow_key) or 0
flow_sum = flow_sum + body_bytes_sent
access:set(flow_key, flow_sum, expire_time)
-- 请求时间统计
local req_time_key = table.concat({host,"-reqt-",timestamp})
local req_sum = access:get(req_time_key) or 0
req_sum = req_sum + request_time
access:set(req_time_key, req_sum, expire_time)
-- banner统计
-- ngx.log(ngx.STDERR, "==>", request_body)
local banner_count = 0
if (request_body ~= nil and request_body ~= '') then
if string.find(request_body, "banner") then
banner_count = 1
end
local req_banner_key = table.concat({host,"-banner-",timestamp})
local req_banner_sum = access:get(req_banner_key) or 0
req_banner_sum = req_banner_sum + banner_count
access:set(req_banner_key, req_banner_sum, expire_time)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment