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