e21e3901647a7da25a627718d798be2811f98386
[prosody.git] / core / loggingmanager.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 --
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9
10 local format = string.format;
11 local setmetatable, rawset, pairs, ipairs, type =
12         setmetatable, rawset, pairs, ipairs, type;
13 local io_open, io_write = io.open, io.write;
14 local math_max, rep = math.max, string.rep;
15 local os_date = os.date;
16 local getstyle, setstyle = require "util.termcolours".getstyle, require "util.termcolours".setstyle;
17
18 if os.getenv("__FLUSH_LOG") then
19         local io_flush = io.flush;
20         local _io_write = io_write;
21         io_write = function(...) _io_write(...); io_flush(); end
22 end
23
24 local config = require "core.configmanager";
25 local logger = require "util.logger";
26 local prosody = prosody;
27
28 _G.log = logger.init("general");
29
30 local _ENV = nil;
31
32 -- The log config used if none specified in the config file (see reload_logging for initialization)
33 local default_logging;
34 local default_file_logging;
35 local default_timestamp = "%b %d %H:%M:%S";
36 -- The actual config loggingmanager is using
37 local logging_config;
38
39 local apply_sink_rules;
40 local log_sink_types = setmetatable({}, { __newindex = function (t, k, v) rawset(t, k, v); apply_sink_rules(k); end; });
41 local get_levels;
42 local logging_levels = { "debug", "info", "warn", "error" }
43
44 -- Put a rule into action. Requires that the sink type has already been registered.
45 -- This function is called automatically when a new sink type is added [see apply_sink_rules()]
46 local function add_rule(sink_config)
47         local sink_maker = log_sink_types[sink_config.to];
48         if not sink_maker then
49                 return; -- No such sink type
50         end
51
52         -- Create sink
53         local sink = sink_maker(sink_config);
54
55         -- Set sink for all chosen levels
56         for level in pairs(get_levels(sink_config.levels or logging_levels)) do
57                 logger.add_level_sink(level, sink);
58         end
59 end
60
61 -- Search for all rules using a particular sink type, and apply
62 -- them. Called automatically when a new sink type is added to
63 -- the log_sink_types table.
64 function apply_sink_rules(sink_type)
65         if type(logging_config) == "table" then
66
67                 for _, level in ipairs(logging_levels) do
68                         if type(logging_config[level]) == "string" then
69                                 local value = logging_config[level];
70                                 if sink_type == "file" and not value:match("^%*") then
71                                         add_rule({
72                                                 to = sink_type;
73                                                 filename = value;
74                                                 timestamps = true;
75                                                 levels = { min = level };
76                                         });
77                                 elseif value == "*"..sink_type then
78                                         add_rule({
79                                                 to = sink_type;
80                                                 levels = { min = level };
81                                         });
82                                 end
83                         end
84                 end
85
86                 for _, sink_config in ipairs(logging_config) do
87                         if (type(sink_config) == "table" and sink_config.to == sink_type) then
88                                 add_rule(sink_config);
89                         elseif (type(sink_config) == "string" and sink_config:match("^%*(.+)") == sink_type) then
90                                 add_rule({ levels = { min = "debug" }, to = sink_type });
91                         end
92                 end
93         elseif type(logging_config) == "string" and (not logging_config:match("^%*")) and sink_type == "file" then
94                 -- User specified simply a filename, and the "file" sink type
95                 -- was just added
96                 for _, sink_config in pairs(default_file_logging) do
97                         sink_config.filename = logging_config;
98                         add_rule(sink_config);
99                         sink_config.filename = nil;
100                 end
101         elseif type(logging_config) == "string" and logging_config:match("^%*(.+)") == sink_type then
102                 -- Log all levels (debug+) to this sink
103                 add_rule({ levels = { min = "debug" }, to = sink_type });
104         end
105 end
106
107
108
109 --- Helper function to get a set of levels given a "criteria" table
110 function get_levels(criteria, set)
111         set = set or {};
112         if type(criteria) == "string" then
113                 set[criteria] = true;
114                 return set;
115         end
116         local min, max = criteria.min, criteria.max;
117         if min or max then
118                 local in_range;
119                 for _, level in ipairs(logging_levels) do
120                         if min == level then
121                                 set[level] = true;
122                                 in_range = true;
123                         elseif max == level then
124                                 set[level] = true;
125                                 return set;
126                         elseif in_range then
127                                 set[level] = true;
128                         end
129                 end
130         end
131
132         for _, level in ipairs(criteria) do
133                 set[level] = true;
134         end
135         return set;
136 end
137
138 -- Initialize config, etc. --
139 local function reload_logging()
140         local old_sink_types = {};
141
142         for name, sink_maker in pairs(log_sink_types) do
143                 old_sink_types[name] = sink_maker;
144                 log_sink_types[name] = nil;
145         end
146
147         logger.reset();
148
149         local debug_mode = config.get("*", "debug");
150
151         default_logging = { { to = "console" , levels = { min = (debug_mode and "debug") or "info" } } };
152         default_file_logging = {
153                 { to = "file", levels = { min = (debug_mode and "debug") or "info" }, timestamps = true }
154         };
155         default_timestamp = "%b %d %H:%M:%S";
156
157         logging_config = config.get("*", "log") or default_logging;
158
159
160         for name, sink_maker in pairs(old_sink_types) do
161                 log_sink_types[name] = sink_maker;
162         end
163
164         prosody.events.fire_event("logging-reloaded");
165 end
166
167 reload_logging();
168 prosody.events.add_handler("config-reloaded", reload_logging);
169
170 --- Definition of built-in logging sinks ---
171
172 -- Null sink, must enter log_sink_types *first*
173 function log_sink_types.nowhere()
174         return function () return false; end;
175 end
176
177 -- Column width for "source" (used by stdout and console)
178 local sourcewidth = 20;
179
180 function log_sink_types.stdout(sink_config)
181         local timestamps = sink_config.timestamps;
182
183         if timestamps == true then
184                 timestamps = default_timestamp; -- Default format
185         end
186
187         return function (name, level, message, ...)
188                 sourcewidth = math_max(#name+2, sourcewidth);
189                 local namelen = #name;
190                 if timestamps then
191                         io_write(os_date(timestamps), " ");
192                 end
193                 if ... then
194                         io_write(name, rep(" ", sourcewidth-namelen), level, "\t", format(message, ...), "\n");
195                 else
196                         io_write(name, rep(" ", sourcewidth-namelen), level, "\t", message, "\n");
197                 end
198         end
199 end
200
201 do
202         local do_pretty_printing = true;
203
204         local logstyles = {};
205         if do_pretty_printing then
206                 logstyles["info"] = getstyle("bold");
207                 logstyles["warn"] = getstyle("bold", "yellow");
208                 logstyles["error"] = getstyle("bold", "red");
209         end
210         function log_sink_types.console(sink_config)
211                 -- Really if we don't want pretty colours then just use plain stdout
212                 if not do_pretty_printing then
213                         return log_sink_types.stdout(sink_config);
214                 end
215
216                 local timestamps = sink_config.timestamps;
217
218                 if timestamps == true then
219                         timestamps = default_timestamp; -- Default format
220                 end
221
222                 return function (name, level, message, ...)
223                         sourcewidth = math_max(#name+2, sourcewidth);
224                         local namelen = #name;
225
226                         if timestamps then
227                                 io_write(os_date(timestamps), " ");
228                         end
229                         io_write(name, rep(" ", sourcewidth-namelen));
230                         setstyle(logstyles[level]);
231                         io_write(level);
232                         setstyle();
233                         if ... then
234                                 io_write("\t", format(message, ...), "\n");
235                         else
236                                 io_write("\t", message, "\n");
237                         end
238                 end
239         end
240 end
241
242 local empty_function = function () end;
243 function log_sink_types.file(sink_config)
244         local log = sink_config.filename;
245         local logfile = io_open(log, "a+");
246         if not logfile then
247                 return empty_function;
248         end
249         local write, flush = logfile.write, logfile.flush;
250
251         local timestamps = sink_config.timestamps;
252
253         if timestamps == nil or timestamps == true then
254                 timestamps = default_timestamp; -- Default format
255         end
256
257         return function (name, level, message, ...)
258                 if timestamps then
259                         write(logfile, os_date(timestamps), " ");
260                 end
261                 if ... then
262                         write(logfile, name, "\t", level, "\t", format(message, ...), "\n");
263                 else
264                         write(logfile, name, "\t" , level, "\t", message, "\n");
265                 end
266                 flush(logfile);
267         end;
268 end
269
270 local function register_sink_type(name, sink_maker)
271         local old_sink_maker = log_sink_types[name];
272         log_sink_types[name] = sink_maker;
273         return old_sink_maker;
274 end
275
276 return {
277         reload_logging = reload_logging;
278         register_sink_type = register_sink_type;
279 }