Prepare required data folder for integration tests
[prosody.git] / util / statsd.lua
blob67481c3670cbabcee1a46439a4b167d14968dc88
1 local socket = require "socket";
3 local time = require "util.time".now
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
10 local sock = socket.udp();
11 sock:setpeername(config.statsd_server, config.statsd_port or 8125);
13 local prefix = (config.prefix or "prosody")..".";
15 local function send_metric(s)
16 return sock:send(prefix..s);
17 end
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
27 local function send_counter(name, amount)
28 return send_metric(name..":"..tostring(amount).."|c");
29 end
31 local function send_duration(name, duration)
32 return send_metric(name..":"..tostring(duration).."|ms");
33 end
35 local function send_histogram_sample(name, sample)
36 return send_metric(name..":"..tostring(sample).."|h");
37 end
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) --luacheck: ignore 212/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;
79 return methods;
80 end
82 return {
83 new = new;