1 module hollow.logger;
2 
3 import std.string;
4 import hollow.outlets.outlet;
5 import hollow.outlets.console;
6 import hollow.formatters.formatter;
7 import hollow.filters.filter;
8 
9 class Logger {
10   string name;
11 
12   Outlet[] outlets;
13   Filter[] filters;
14   Formatter formatter;
15 
16   this(string name) {
17     this.name = name;
18 
19     this.formatter = new Formatter(this.name);
20   }
21 
22   this(string name, Outlet outlet) {
23     this.name = name;
24     this.formatter = new Formatter(this.name);
25     this.outlets ~= outlet;
26   }
27 
28   void addOutlet(Outlet outlet) {
29     outlet.open();
30     this.outlets ~= outlet;
31   }
32 
33   void addFilter(Filter filter) {
34     this.filters ~= filter;
35   }
36 
37   void close() {
38     foreach (i, outlet; this.outlets) {
39       outlet.close();
40     }
41   }
42 
43   void write(string line) {
44     foreach (i, filter; this.filters) {
45       if (!filter.shouldWriteLine(line)) {
46         return;
47       }
48     }
49 
50     foreach (i, outlet; this.outlets) {
51       outlet.writeLine(line);
52     }
53   }
54 
55   void TRACE(T...)(Throwable t, string fmt, T args) {
56     string data = format(fmt, args) ~ ":\n" ~ t.toString();
57 
58     this.write(this.formatter.format("EXCEPTION", data));
59   }
60 
61   void INFO(T...)(string fmt, T args) {
62     this.write(this.formatter.format("INFO", format(fmt, args)));
63   }
64 
65   void DEBUG(T...)(string fmt, T args) {
66     this.write(this.formatter.format("DEBUG", format(fmt, args)));
67   }
68 
69   void WARNING(T...)(string fmt, T args) {
70     this.write(this.formatter.format("WARNING", format(fmt, args)));
71   }
72 
73   void ERROR(T...)(string fmt, T args) {
74     this.write(this.formatter.format("ERROR", format(fmt, args)));
75   }
76 }
77 
78 Logger newLogger(string name) {
79   Logger log = new Logger(name);
80   log.addOutlet(new ConsoleOutlet());
81   return log;
82 }
83 
84 unittest {
85   import hollow.outlets.file;
86 
87   Logger log = new Logger("test");
88   FileOutlet f = new FileOutlet("/tmp/hollow_test");
89   log.addOutlet(f);
90 
91   log.INFO("test %s, %s, %s", 1, "LOL", log);
92   log.DEBUG("test %s, %s, %s", 1, "LOL", log);
93   log.WARNING("test %s, %s, %s", 1, "LOL", log);
94   log.ERROR("test %s, %s, %s", 1, "LOL", log);
95 
96   try {
97     throw new Exception("test");
98   } catch (Exception e) {
99     log.TRACE(e, "test %s, %s, %s", 1, "LOL", log);
100   }
101 }
102