Merge waqas with waqas
[prosody.git] / util / logger.lua
1 -- Prosody IM v0.3
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 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         local namelen = #name;
37         return  function (level, message, ...)
38                                 if outfunction then return outfunction(name, level, message, ...); end
39                                 
40                                 sourcewidth = math_max(#name+2, sourcewidth);
41                                 if ... then 
42                                         io_write(name, rep(" ", sourcewidth-namelen), getstring(logstyles[level], level), "\t", format(message, ...), "\n");
43                                 else
44                                         io_write(name, rep(" ", sourcewidth-namelen), getstring(logstyles[level], level), "\t", message, "\n");
45                                 end
46                         end
47 end
48
49 function setwriter(f)
50         local old_func = outfunction;
51         if not f then outfunction = nil; return true, old_func; end
52         local ok, ret = pcall(f, "logger", "info", "Switched logging output successfully");
53         if ok then
54                 outfunction = f;
55                 ret = old_func;
56         end
57         return ok, ret;
58 end
59
60 return _M;