]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/logger.h
Fix Windows build
[user/henk/code/inspircd.git] / include / logger.h
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
5  *   Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
6  *
7  * This file is part of InspIRCd.  InspIRCd is free software: you can
8  * redistribute it and/or modify it under the terms of the GNU General Public
9  * License as published by the Free Software Foundation, version 2.
10  *
11  * This program is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
14  * details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20
21 #pragma once
22
23 /** Simple wrapper providing periodic flushing to a disk-backed file.
24  */
25 class CoreExport FileWriter
26 {
27  protected:
28         /** The log file (fd is inside this somewhere,
29          * we get it out with fileno())
30          */
31         FILE* log;
32
33         /** Number of write operations that have occured
34          */
35         int writeops;
36
37  public:
38         /** The constructor takes an already opened logfile.
39          */
40         FileWriter(FILE* logfile);
41
42         /** Write one or more preformatted log lines.
43          * If the data cannot be written immediately,
44          * this class will insert itself into the
45          * SocketEngine, and register a write event,
46          * and when the write event occurs it will
47          * attempt again to write the data.
48          */
49         void WriteLogLine(const std::string &line);
50
51         /** Close the log file and cancel any events.
52          */
53         virtual ~FileWriter();
54 };
55
56
57
58 /*
59  * New world logging!
60  * The brief summary:
61  *  Logging used to be a simple affair, a FILE * handled by a nonblocking logging class inheriting from EventHandler, that was inserted
62  *  into the socket engine, and wrote lines. If nofork was on, it was printf()'d.
63  *
64  *  We decided to horribly overcomplicate matters, and create vastly customisable logging. LogManager and LogStream form the visible basis
65  *  of the new interface. Basically, a LogStream can be inherited to do different things with logging output. We inherit from it once in core
66  *  to create a FileLogStream, that writes to a file, for example. Different LogStreams can hook different types of log messages, and different
67  *  levels of output too, for extreme customisation. Multiple LogStreams can hook the same message/levels of output, meaning that e.g. output
68  *  can go to a channel as well as a file.
69  *
70  *  HOW THIS WORKS
71  *   LogManager handles all instances of LogStreams, classes derived from LogStream are instantiated and passed to it.
72  */
73
74 /** LogStream base class. Modules (and other stuff) inherit from this to decide what logging they are interested in, and what to do with it.
75  */
76 class CoreExport LogStream : public classbase
77 {
78  protected:
79         int loglvl;
80  public:
81         LogStream(int loglevel) : loglvl(loglevel)
82         {
83         }
84
85         /* A LogStream's destructor should do whatever it needs to close any resources it was using (or indicate that it is no longer using a resource
86          * in the event that the resource is shared, see for example FileLogStream).
87          */
88         virtual ~LogStream() { }
89
90         /** Changes the loglevel for this LogStream on-the-fly.
91          * This is needed for -nofork. But other LogStreams could use it to change loglevels.
92          */
93         void ChangeLevel(int lvl) { this->loglvl = lvl; }
94
95         /** Called when there is stuff to log for this particular logstream. The derived class may take no action with it, or do what it
96          * wants with the output, basically. loglevel and type are primarily for informational purposes (the level and type of the event triggered)
97          * and msg is, of course, the actual message to log.
98          */
99         virtual void OnLog(int loglevel, const std::string &type, const std::string &msg) = 0;
100 };
101
102 typedef std::map<FileWriter*, int> FileLogMap;
103
104 class CoreExport LogManager
105 {
106  private:
107         /** Lock variable, set to true when a log is in progress, which prevents further loggging from happening and creating a loop.
108          */
109         bool Logging;
110
111         /** Map of active log types and what LogStreams will receive them.
112          */
113         std::map<std::string, std::vector<LogStream *> > LogStreams;
114
115         /** Refcount map of all LogStreams managed by LogManager.
116          * If a logstream is not listed here, it won't be automatically closed by LogManager, even if it's loaded in one of the other lists.
117          */
118         std::map<LogStream *, int> AllLogStreams;
119
120         /** LogStreams with type * (which means everything), and a list a logtypes they are excluded from (eg for "* -USERINPUT -USEROUTPUT").
121          */
122         std::map<LogStream *, std::vector<std::string> > GlobalLogStreams;
123
124         /** Refcounted map of all FileWriters in use by FileLogStreams, for file stream sharing.
125          */
126         FileLogMap FileLogs;
127
128  public:
129
130         LogManager();
131         ~LogManager();
132
133         /** Adds a FileWriter instance to LogManager, or increments the reference count of an existing instance.
134          * Used for file-stream sharing for FileLogStreams.
135          */
136         void AddLoggerRef(FileWriter* fw)
137         {
138                 FileLogMap::iterator i = FileLogs.find(fw);
139                 if (i == FileLogs.end())
140                 {
141                         FileLogs.insert(std::make_pair(fw, 1));
142                 }
143                 else
144                 {
145                         ++i->second;
146                 }
147         }
148
149         /** Indicates that a FileWriter reference has been removed. Reference count is decreased, and if zeroed, the FileWriter is closed.
150          */
151         void DelLoggerRef(FileWriter* fw)
152         {
153                 FileLogMap::iterator i = FileLogs.find(fw);
154                 if (i == FileLogs.end()) return; /* Maybe should log this? */
155                 if (--i->second < 1)
156                 {
157                         delete i->first;
158                         FileLogs.erase(i);
159                 }
160         }
161
162         /** Opens all logfiles defined in the configuration file using \<log method="file">.
163          */
164         void OpenFileLogs();
165
166         /** Removes all LogStreams, meaning they have to be readded for logging to continue.
167          * Only LogStreams that were listed in AllLogStreams are actually closed.
168          */
169         void CloseLogs();
170
171         /** Adds a single LogStream to multiple logtypes.
172          * This automatically handles things like "* -USERINPUT -USEROUTPUT" to mean all but USERINPUT and USEROUTPUT types.
173          * It is not a good idea to mix values of autoclose for the same LogStream.
174          * @param type The type string (from configuration, or whatever) to parse.
175          * @param l The LogStream to add.
176          * @param autoclose True to have the LogStream automatically closed when all references to it are removed from LogManager. False to leave it open.
177          */
178         void AddLogTypes(const std::string &type, LogStream *l, bool autoclose);
179
180         /** Registers a new logstream into the logging core, so it can be called for future events
181          * It is not a good idea to mix values of autoclose for the same LogStream.
182          * @param type The type to add this LogStream to.
183          * @param l The LogStream to add.
184          * @param autoclose True to have the LogStream automatically closed when all references to it are removed from LogManager. False to leave it open.
185          * @return True if the LogStream was added successfully, False otherwise.
186          */
187         bool AddLogType(const std::string &type, LogStream *l, bool autoclose);
188
189         /** Removes a logstream from the core. After removal, it will not recieve further events.
190          * If the LogStream was ever added with autoclose, it will be closed after this call (this means the pointer won't be valid anymore).
191          */
192         void DelLogStream(LogStream* l);
193
194         /** Removes a LogStream from a single type. If the LogStream has been registered for "*" it will still receive the type unless you remove it from "*" specifically.
195          * If the LogStream was added with autoclose set to true, then when the last occurrence of the stream is removed it will automatically be closed (freed).
196          */
197         bool DelLogType(const std::string &type, LogStream *l);
198
199         /** Logs an event, sending it to all LogStreams registered for the type.
200          * @param type Log message type (ex: "USERINPUT", "MODULE", ...)
201          * @param loglevel Log message level (LOG_DEBUG, LOG_VERBOSE, LOG_DEFAULT, LOG_SPARSE, LOG_NONE)
202          * @param msg The message to be logged (literal).
203          */
204         void Log(const std::string &type, int loglevel, const std::string &msg);
205
206         /** Logs an event, sending it to all LogStreams registered for the type.
207          * @param type Log message type (ex: "USERINPUT", "MODULE", ...)
208          * @param loglevel Log message level (LOG_DEBUG, LOG_VERBOSE, LOG_DEFAULT, LOG_SPARSE, LOG_NONE)
209          * @param fmt The format of the message to be logged. See your C manual on printf() for details.
210          */
211         void Log(const std::string &type, int loglevel, const char *fmt, ...) CUSTOM_PRINTF(4, 5);
212 };