-
Notifications
You must be signed in to change notification settings - Fork 26
/
logging.lua
74 lines (56 loc) · 1.58 KB
/
logging.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
-- Copyright (C) 2012 Matthieu Tourne
-- @author Matthieu Tourne <[email protected]>
-- Simple helper functions for logging
local logging = {}
local module = logging
local function incr(dict, key, increment)
increment = increment or 1
local newval, err = dict:incr(key, increment)
if err then
dict:set(key, increment)
newval = increment
end
return newval
end
function logging.add_plot(dict, key, value)
local sum_key = key .. "-sum"
local count_key = key .. "-count"
local start_time_key = key .. "-start_time"
local start_time = dict:get(start_time_key)
if not start_time then
ngx.log(ngx.ERR, 'now: ', ngx.now())
dict:set(start_time_key, ngx.now())
end
local sum = incr(dict, sum_key, value)
incr(dict, count_key)
end
function logging.get_plot(dict, key)
local sum_key = key .. "-sum"
local count_key = key .. "-count"
local start_time_key = key .. "-start_time"
local elapsed_time = 0
local avg = 0
local start_time = dict:get(start_time_key)
if start_time then
elapsed_time = ngx.now() - start_time
end
dict:delete(start_time_key)
local count = dict:get(count_key) or 0
dict:delete(count_key)
local sum = dict:get(sum_key) or 0
dict:delete(sum_key)
if count > 0 then
avg = sum / count
end
return count, avg, elapsed_time
end
-- safety net
local module_mt = {
__newindex = (
function (table, key, val)
error('Attempt to write to undeclared variable "' .. key .. '"')
end),
}
setmetatable(module, module_mt)
-- expose the module
return logging