Nginx监控请求lua脚本


Nginx监控请求lua脚本
 
当应答状态码不是200时,通过udp向服务器发送报告。
monitor.lua
[plain] 
--   
-- Config Nginx.conf:  
--  
-- set $str $uri;  
-- content_by_lua_file;  
--   
-- location /proxy {  
--    proxy_pass http://{your-server}$str;  
-- }  
--  
  
--  
-- Extends int to 4 byte  
--  
function pad32bit(num)  
    local hex = ""  
    local rem = num  
    for i=1,4 do  
      local bit = rem % 256  
      rem = math.floor(rem /256)  
  
      hex = hex .. string.char(bit)  
    end  
    return hex  
end  
  
local url = ngx.var.uri  
local res = ngx.location.capture("/proxy", {vars = {str = url} })  
  
-- Response  
ngx.say(res.body)  
  
-- Send udp message  
if res.status ~= 200 then  
  
-- Protocol  
-- Length | version | Top-Level no (4) | Second-Level no | json body  
  
  --local mydata = require "mydata"  
  --local udpsock = mydata:socket()  
  
  local udpsock = ngx.socket.udp()  
  udpsock:settimeout(0)  
  local ok, err = udpsock:setpeername("224.3.29.71", 10000)  
  
  local body = "host:" .. ngx.var.host  .. ", url:" .. url .. ", status:" .. res.status  
  local leng = 4 + 3 + string.len(body)  
  
  local msg = pad32bit(leng) .. "\1\4\1" .. body  
  
  ngx.say("<!--" .. msg .. "-->")  
  
  local ok, err = udpsock:send(msg)  
  
end  
 
Nginx.conf
[plain] 
upstream web{  
     server 127.0.0.1:8080;  
     server 127.0.0.1:8081;  
}  
  
server {  
    listen       80;  
    server_name  localhost;  
  
    #charset koi8-r;  
  
    location / {  
        root   html;  
        index  index.html index.htm;  
  
        set $str $uri;  
        content_by_lua_file /home/hailin/monitor.lua;  
    }  
  
    location /proxy {  
         resolver 8.8.8.8;  
  
         proxy_pass http://web$str;  
    }  
 

相关内容

    暂无相关文章