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