]> git.lizzy.rs Git - dragonfireclient.git/blob - src/log.cpp
4f77101f932efde992e09d2c433ef6e8d9a3854f
[dragonfireclient.git] / src / log.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "log.h"
21
22 #include "threading/mutex_auto_lock.h"
23 #include "debug.h"
24 #include "gettime.h"
25 #include "porting.h"
26 #include "config.h"
27 #include "exceptions.h"
28 #include "util/numeric.h"
29 #include "log.h"
30
31 #include <sstream>
32 #include <iostream>
33 #include <algorithm>
34 #include <cerrno>
35 #include <cstring>
36
37 class StringBuffer : public std::streambuf {
38 public:
39         StringBuffer() {}
40
41         int overflow(int c);
42         virtual void flush(const std::string &buf) = 0;
43         std::streamsize xsputn(const char *s, std::streamsize n);
44         void push_back(char c);
45
46 private:
47         std::string buffer;
48 };
49
50
51 class LogBuffer : public StringBuffer {
52 public:
53         LogBuffer(Logger &logger, LogLevel lev) :
54                 logger(logger),
55                 level(lev)
56         {}
57
58         void flush(const std::string &buffer);
59
60 private:
61         Logger &logger;
62         LogLevel level;
63 };
64
65
66 class RawLogBuffer : public StringBuffer {
67 public:
68         void flush(const std::string &buffer);
69 };
70
71
72 #ifdef __ANDROID__
73 static unsigned int level_to_android[] = {
74         ANDROID_LOG_INFO,     // LL_NONE
75         //ANDROID_LOG_FATAL,
76         ANDROID_LOG_ERROR,    // LL_ERROR
77         ANDROID_LOG_WARN,     // LL_WARNING
78         ANDROID_LOG_WARN,     // LL_ACTION
79         //ANDROID_LOG_INFO,
80         ANDROID_LOG_DEBUG,    // LL_INFO
81         ANDROID_LOG_VERBOSE,  // LL_VERBOSE
82
83 };
84 #endif
85
86 ////
87 //// Globals
88 ////
89
90 Logger g_logger;
91
92 StreamLogOutput stdout_output(std::cout);
93 StreamLogOutput stderr_output(std::cerr);
94 std::ostream null_stream(NULL);
95
96 RawLogBuffer raw_buf;
97
98 LogBuffer none_buf(g_logger, LL_NONE);
99 LogBuffer error_buf(g_logger, LL_ERROR);
100 LogBuffer warning_buf(g_logger, LL_WARNING);
101 LogBuffer action_buf(g_logger, LL_ACTION);
102 LogBuffer info_buf(g_logger, LL_INFO);
103 LogBuffer verbose_buf(g_logger, LL_VERBOSE);
104
105 // Connection
106 std::ostream *dout_con_ptr = &null_stream;
107 std::ostream *derr_con_ptr = &verbosestream;
108
109 // Server
110 std::ostream *dout_server_ptr = &infostream;
111 std::ostream *derr_server_ptr = &errorstream;
112
113 #ifndef SERVER
114 // Client
115 std::ostream *dout_client_ptr = &infostream;
116 std::ostream *derr_client_ptr = &errorstream;
117 #endif
118
119 std::ostream rawstream(&raw_buf);
120 std::ostream dstream(&none_buf);
121 std::ostream errorstream(&error_buf);
122 std::ostream warningstream(&warning_buf);
123 std::ostream actionstream(&action_buf);
124 std::ostream infostream(&info_buf);
125 std::ostream verbosestream(&verbose_buf);
126
127
128 ///////////////////////////////////////////////////////////////////////////////
129
130
131 ////
132 //// Logger
133 ////
134
135 LogLevel Logger::stringToLevel(const std::string &name)
136 {
137         if (name == "none")
138                 return LL_NONE;
139         else if (name == "error")
140                 return LL_ERROR;
141         else if (name == "warning")
142                 return LL_WARNING;
143         else if (name == "action")
144                 return LL_ACTION;
145         else if (name == "info")
146                 return LL_INFO;
147         else if (name == "verbose")
148                 return LL_VERBOSE;
149         else
150                 return LL_MAX;
151 }
152
153 void Logger::addOutput(ILogOutput *out)
154 {
155         addOutputMaxLevel(out, LL_MAX);
156 }
157
158 void Logger::addOutput(ILogOutput *out, LogLevel lev)
159 {
160         m_outputs[lev].push_back(out);
161 }
162
163 void Logger::addOutputMaxLevel(ILogOutput *out, LogLevel lev)
164 {
165         for (size_t i = 0; i <= lev; i++)
166                 m_outputs[i].push_back(out);
167 }
168
169 void Logger::removeOutput(ILogOutput *out)
170 {
171         for (size_t i = 0; i < LL_MAX; i++) {
172                 std::vector<ILogOutput *>::iterator it;
173
174                 it = std::find(m_outputs[i].begin(), m_outputs[i].end(), out);
175                 if (it != m_outputs[i].end())
176                         m_outputs[i].erase(it);
177         }
178 }
179
180 void Logger::setLevelSilenced(LogLevel lev, bool silenced)
181 {
182         m_silenced_levels[lev] = silenced;
183 }
184
185 void Logger::registerThread(const std::string &name)
186 {
187         threadid_t id = get_current_thread_id();
188         MutexAutoLock lock(m_mutex);
189         m_thread_names[id] = name;
190 }
191
192 void Logger::deregisterThread()
193 {
194         threadid_t id = get_current_thread_id();
195         MutexAutoLock lock(m_mutex);
196         m_thread_names.erase(id);
197 }
198
199 const std::string Logger::getLevelLabel(LogLevel lev)
200 {
201         static const std::string names[] = {
202                 "",
203                 "ERROR",
204                 "WARNING",
205                 "ACTION",
206                 "INFO",
207                 "VERBOSE",
208         };
209         assert(lev < LL_MAX && lev >= 0);
210         assert(ARRLEN(names) == LL_MAX);
211         return names[lev];
212 }
213
214 const std::string Logger::getThreadName()
215 {
216         std::map<threadid_t, std::string>::const_iterator it;
217
218         threadid_t id = get_current_thread_id();
219         it = m_thread_names.find(id);
220         if (it != m_thread_names.end())
221                 return it->second;
222
223         std::ostringstream os;
224         os << "#0x" << std::hex << id;
225         return os.str();
226 }
227
228 void Logger::log(LogLevel lev, const std::string &text)
229 {
230         if (m_silenced_levels[lev])
231                 return;
232
233         const std::string thread_name = getThreadName();
234         const std::string label = getLevelLabel(lev);
235         std::ostringstream os(std::ios_base::binary);
236         os << getTimestamp() << ": " << label << "[" << thread_name << "]: " << text;
237
238         logToSystem(lev, text);
239         logToOutputs(lev, os.str());
240 }
241
242 void Logger::logRaw(LogLevel lev, const std::string &text)
243 {
244         if (m_silenced_levels[lev])
245                 return;
246
247         logToSystem(lev, text);
248         logToOutputs(lev, text);
249 }
250
251 void Logger::logToSystem(LogLevel lev, const std::string &text)
252 {
253 #ifdef __ANDROID__
254         assert(ARRLEN(level_to_android) == LL_MAX);
255         __android_log_print(level_to_android[lev],
256                 PROJECT_NAME_C, "%s", text.c_str());
257 #endif
258 }
259
260 void Logger::logToOutputs(LogLevel lev, const std::string &text)
261 {
262         MutexAutoLock lock(m_mutex);
263         for (size_t i = 0; i != m_outputs[lev].size(); i++)
264                 m_outputs[lev][i]->log(text);
265 }
266
267
268 ////
269 //// *LogOutput methods
270 ////
271
272 void FileLogOutput::open(const std::string &filename)
273 {
274         stream.open(filename.c_str(), std::ios::app | std::ios::ate);
275         if (!stream.good())
276                 throw FileNotGoodException("Failed to open log file " +
277                         filename + ": " + strerror(errno));
278         stream << "\n\n"
279                    "-------------" << std::endl
280                 << "  Separator" << std::endl
281                 << "-------------\n" << std::endl;
282 }
283
284
285
286 ////
287 //// *Buffer methods
288 ////
289
290 int StringBuffer::overflow(int c)
291 {
292         push_back(c);
293         return c;
294 }
295
296
297 std::streamsize StringBuffer::xsputn(const char *s, std::streamsize n)
298 {
299         for (int i = 0; i < n; ++i)
300                 push_back(s[i]);
301         return n;
302 }
303
304 void StringBuffer::push_back(char c)
305 {
306         if (c == '\n' || c == '\r') {
307                 if (!buffer.empty())
308                         flush(buffer);
309                 buffer.clear();
310         } else {
311                 buffer.push_back(c);
312         }
313 }
314
315
316
317
318 void LogBuffer::flush(const std::string &buffer)
319 {
320         logger.log(level, buffer);
321 }
322
323 void RawLogBuffer::flush(const std::string &buffer)
324 {
325         g_logger.logRaw(LL_NONE, buffer);
326 }