Created
February 9, 2014 19:59
-
-
Save knyar/8905045 to your computer and use it in GitHub Desktop.
statsd interface for nginx (via ngx_lua)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- ---------------------------------------------------------------------------- | |
-- statsd interface for nginx | |
-- (c) 2014 Anton Tolchanov | |
-- https://gist.github.com/knyar/8905045 | |
-- | |
-- Usage: | |
-- 1. install nginx with ngx_lua; | |
-- 2. put this file as statsd.lua somewhere (/var/lib/nginx/lua/ will do); | |
-- 3. initialize stats in init_by_lua: | |
-- http { | |
-- ... | |
-- lua_package_path "/var/lib/nginx/lua/?.lua"; | |
-- init_by_lua 'statsd = require("statsd")'; | |
-- ... | |
-- } | |
-- 4. send data to statsd from log_by_lua: | |
-- server { | |
-- ... | |
-- log_by_lua ' | |
-- statsd.log( | |
-- statsd.incr("nginx.site01.status." .. ngx.var.status), | |
-- statsd.time("nginx.site01.req_time", ngx.now() - ngx.req.start_time()) | |
-- ) | |
-- '; | |
-- } | |
-- | |
-- See http://wiki.nginx.org/HttpLuaModule for more information about ngx_lua | |
-- ---------------------------------------------------------------------------- | |
local Statsd = {} | |
Statsd.time = function (counter, n) return counter .. ":" .. n .. "|ms" end | |
Statsd.count = function (counter, n) return counter .. ":" .. n .. "|c" end | |
Statsd.incr = function (counter) return Statsd.count(counter, 1) end | |
Statsd.send = function (premature, metrics) | |
local udp = ngx.socket.udp() | |
udp:setpeername("127.0.0.1", 8125) | |
udp:send(metrics) | |
udp:close() | |
end | |
Statsd.log = function (...) | |
-- This function will be run from log_by_lua where socket operations are | |
-- not available. A work-around is to schedule a nginx timer to run | |
-- Statsd.send() for us. `arg` contains all parameters to this function. | |
local ok, err = ngx.timer.at(0, Statsd.send, table.concat(arg, "\n")) | |
if not ok then | |
ngx.log(ngx.ERR, "cannot create timer: ", err) | |
end | |
end | |
return Statsd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment