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