Software / code / prosody
Comparison
util/statsd.lua @ 7522:ebf2e77ac8a7
statsmanager, util.statsd: Add built-in statsd provider
| author | Matthew Wild <mwild1@gmail.com> |
|---|---|
| date | Wed, 27 Jul 2016 14:06:10 +0100 |
| child | 7701:672a863105f6 |
comparison
equal
deleted
inserted
replaced
| 7521:1c8b63fe6472 | 7522:ebf2e77ac8a7 |
|---|---|
| 1 local socket = require "socket"; | |
| 2 | |
| 3 local time = require "socket".gettime; | |
| 4 | |
| 5 local function new(config) | |
| 6 if not config or not config.statsd_server then | |
| 7 return nil, "No statsd server specified in the config, please see https://prosody.im/doc/statistics"; | |
| 8 end | |
| 9 | |
| 10 local sock = socket.udp(); | |
| 11 sock:setpeername(config.statsd_server, config.statsd_port or 8125); | |
| 12 | |
| 13 local prefix = (config.prefix or "prosody").."."; | |
| 14 | |
| 15 local function send_metric(s) | |
| 16 return sock:send(prefix..s); | |
| 17 end | |
| 18 | |
| 19 local function send_gauge(name, amount, relative) | |
| 20 local s_amount = tostring(amount); | |
| 21 if relative and amount > 0 then | |
| 22 s_amount = "+"..s_amount; | |
| 23 end | |
| 24 return send_metric(name..":"..s_amount.."|g"); | |
| 25 end | |
| 26 | |
| 27 local function send_counter(name, amount) | |
| 28 return send_metric(name..":"..tostring(amount).."|c"); | |
| 29 end | |
| 30 | |
| 31 local function send_duration(name, duration) | |
| 32 return send_metric(name..":"..tostring(duration).."|ms"); | |
| 33 end | |
| 34 | |
| 35 local function send_histogram_sample(name, sample) | |
| 36 return send_metric(name..":"..tostring(sample).."|h"); | |
| 37 end | |
| 38 | |
| 39 local methods; | |
| 40 methods = { | |
| 41 amount = function (name, initial) | |
| 42 if initial then | |
| 43 send_gauge(name, initial); | |
| 44 end | |
| 45 return function (new_v) send_gauge(name, new_v); end | |
| 46 end; | |
| 47 counter = function (name, initial) | |
| 48 return function (delta) | |
| 49 send_gauge(name, delta, true); | |
| 50 end; | |
| 51 end; | |
| 52 rate = function (name) | |
| 53 return function () | |
| 54 send_counter(name, 1); | |
| 55 end; | |
| 56 end; | |
| 57 distribution = function (name, unit, type) --luacheck: ignore 212/unit 212/type | |
| 58 return function (value) | |
| 59 send_histogram_sample(name, value); | |
| 60 end; | |
| 61 end; | |
| 62 sizes = function (name) | |
| 63 name = name.."_size"; | |
| 64 return function (value) | |
| 65 send_histogram_sample(name, value); | |
| 66 end; | |
| 67 end; | |
| 68 times = function (name) | |
| 69 return function () | |
| 70 local start_time = time(); | |
| 71 return function () | |
| 72 local end_time = time(); | |
| 73 local duration = end_time - start_time; | |
| 74 send_duration(name, duration*1000); | |
| 75 end | |
| 76 end; | |
| 77 end; | |
| 78 }; | |
| 79 return methods; | |
| 80 end | |
| 81 | |
| 82 return { | |
| 83 new = new; | |
| 84 } |