GPL->MIT!
[prosody.git] / util / logger.lua
1 -- Prosody IM v0.2
2 -- Copyright (C) 2008 Matthew Wild
3 -- Copyright (C) 2008 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 local format, rep = string.format, string.rep;
10 local io_write = io.write;
11 local pcall = pcall;
12 local debug = debug;
13 local tostring = tostring;
14 local math_max = math.max;
15
16 local getstyle, getstring = require "util.termcolours".getstyle, require "util.termcolours".getstring;
17 local do_pretty_printing = not os.getenv("WINDIR");
18
19 module "logger"
20
21 local logstyles = {};
22
23 --TODO: This should be done in config, but we don't have proper config yet
24 if do_pretty_printing then
25         logstyles["info"] = getstyle("bold");
26         logstyles["warn"] = getstyle("bold", "yellow");
27         logstyles["error"] = getstyle("bold", "red");
28 end
29
30 local sourcewidth = 20;
31
32 local outfunction = nil;
33
34 function init(name)
35         --name = nil; -- While this line is not commented, will automatically fill in file/line number info
36         sourcewidth = math_max(#name+2, sourcewidth);
37         local namelen = #name;
38         return  function (level, message, ...)
39                                 if not name then
40                                         local inf = debug.getinfo(3, 'Snl');
41                                         level = level .. ","..tostring(inf.short_src):match("[^/]*$")..":"..inf.currentline;
42                                 end
43                                 
44                                 if outfunction then return outfunction(name, level, message, ...); end
45                                 
46                                 if ... then 
47                                         io_write(name, rep(" ", sourcewidth-namelen), getstring(logstyles[level], level), "\t", format(message, ...), "\n");
48                                 else
49                                         io_write(name, rep(" ", sourcewidth-namelen), getstring(logstyles[level], level), "\t", message, "\n");
50                                 end
51                         end
52 end
53
54 function setwriter(f)
55         local old_func = outfunction;
56         if not f then outfunction = nil; return true, old_func; end
57         local ok, ret = pcall(f, "logger", "info", "Switched logging output successfully");
58         if ok then
59                 outfunction = f;
60                 ret = old_func;
61         end
62         return ok, ret;
63 end
64
65 return _M;