-
Notifications
You must be signed in to change notification settings - Fork 3
/
Logger.lua
127 lines (71 loc) · 2.08 KB
/
Logger.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
-- Logger.lua
-- Implements a logger that can output log messages and filter them based on loglevel
local Logger =
{
-- The various log levels:
ERROR = 9, -- Emitting this log also prints stacktrace and terminates the entire program
WARNING = 5,
INFO = 4,
DEBUG = 3,
TRACE = 1,
}
-- If currentLogLevel is higher than message's loglevel, the message won't be output
Logger.currentLogLevel = Logger.DEBUG
-- Store the "error" function as of loading this file, so that client code may replace it without affecting us:
local error = error
--- Creates a new logger instance based on the parsed options given
function Logger:new(a_Options)
-- Check params:
assert(type(self) == "table")
assert(type(a_Options) == "table")
local res =
{
currentLogLevel = self.currentLogLevel or a_Options.logLevel or Logger.DEBUG,
}
setmetatable(res, self)
self.__index = self
return res
end
--- Common logging entrypoint, receives all log messages
function Logger:log(a_LogLevel, a_Format, ...)
-- Check params:
assert(self)
assert(type(a_Format) == "string")
-- If loglevel too high for this message, bail out:
if (a_LogLevel < self.currentLogLevel) then
return
end
-- Output the message
print(string.format(a_Format, ...))
io.stdout:flush()
end
--- Logs the message with an ERROR level and calls global "error" with the same message
-- Usually this terminates the program
function Logger:error(a_Level, a_Fmt, ...)
assert(self)
assert(type(a_Level) == "number")
assert(type(a_Fmt) == "string")
self:log(Logger.ERROR, a_Fmt, ...)
error(string.format(a_Fmt, ...), a_Level)
end
--- Logs the message with a WARNING level
function Logger:warning(...)
assert(self)
self:log(Logger.WARNING, ...)
end
--- Logs the message with an INFO level
function Logger:info(...)
assert(self)
self:log(Logger.INFO, ...)
end
--- Logs the message with a DEBUG level
function Logger:debug(...)
assert(self)
self:log(Logger.DEBUG, ...)
end
--- Logs the message with a TRACE level
function Logger:trace(...)
assert(self)
self:log(Logger.TRACE, ...)
end
return Logger