]> git.lizzy.rs Git - minetest.git/blob - src/log.cpp
600e715c12680653379b935551aa2e48384bbffe
[minetest.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 //// Globals
73 ////
74
75 Logger g_logger;
76
77 StreamLogOutput stdout_output(std::cout);
78 StreamLogOutput stderr_output(std::cerr);
79 std::ostream null_stream(NULL);
80
81 RawLogBuffer raw_buf;
82
83 LogBuffer none_buf(g_logger, LL_NONE);
84 LogBuffer error_buf(g_logger, LL_ERROR);
85 LogBuffer warning_buf(g_logger, LL_WARNING);
86 LogBuffer action_buf(g_logger, LL_ACTION);
87 LogBuffer info_buf(g_logger, LL_INFO);
88 LogBuffer verbose_buf(g_logger, LL_VERBOSE);
89
90 // Connection
91 std::ostream *dout_con_ptr = &null_stream;
92 std::ostream *derr_con_ptr = &verbosestream;
93
94 // Server
95 std::ostream *dout_server_ptr = &infostream;
96 std::ostream *derr_server_ptr = &errorstream;
97
98 #ifndef SERVER
99 // Client
100 std::ostream *dout_client_ptr = &infostream;
101 std::ostream *derr_client_ptr = &errorstream;
102 #endif
103
104 std::ostream rawstream(&raw_buf);
105 std::ostream dstream(&none_buf);
106 std::ostream errorstream(&error_buf);
107 std::ostream warningstream(&warning_buf);
108 std::ostream actionstream(&action_buf);
109 std::ostream infostream(&info_buf);
110 std::ostream verbosestream(&verbose_buf);
111
112 // Android
113 #ifdef __ANDROID__
114
115 static unsigned int g_level_to_android[] = {
116         ANDROID_LOG_INFO,     // LL_NONE
117         //ANDROID_LOG_FATAL,
118         ANDROID_LOG_ERROR,    // LL_ERROR
119         ANDROID_LOG_WARN,     // LL_WARNING
120         ANDROID_LOG_WARN,     // LL_ACTION
121         //ANDROID_LOG_INFO,
122         ANDROID_LOG_DEBUG,    // LL_INFO
123         ANDROID_LOG_VERBOSE,  // LL_VERBOSE
124 };
125
126 class AndroidSystemLogOutput : public ICombinedLogOutput {
127         public:
128                 AndroidSystemLogOutput()
129                 {
130                         g_logger.addOutput(this);
131                 }
132                 ~AndroidSystemLogOutput()
133                 {
134                         g_logger.removeOutput(this);
135                 }
136                 void logRaw(LogLevel lev, const std::string &line)
137                 {
138                         STATIC_ASSERT(ARRLEN(g_level_to_android) == LL_MAX,
139                                 mismatch_between_android_and_internal_loglevels);
140                         __android_log_print(g_level_to_android[lev],
141                                 PROJECT_NAME_C, "%s", line.c_str());
142                 }
143 };
144
145 AndroidSystemLogOutput g_android_log_output;
146
147 #endif
148
149 ///////////////////////////////////////////////////////////////////////////////
150
151
152 ////
153 //// Logger
154 ////
155
156 LogLevel Logger::stringToLevel(const std::string &name)
157 {
158         if (name == "none")
159                 return LL_NONE;
160         else if (name == "error")
161                 return LL_ERROR;
162         else if (name == "warning")
163                 return LL_WARNING;
164         else if (name == "action")
165                 return LL_ACTION;
166         else if (name == "info")
167                 return LL_INFO;
168         else if (name == "verbose")
169                 return LL_VERBOSE;
170         else
171                 return LL_MAX;
172 }
173
174 void Logger::addOutput(ILogOutput *out)
175 {
176         addOutputMaxLevel(out, (LogLevel)(LL_MAX - 1));
177 }
178
179 void Logger::addOutput(ILogOutput *out, LogLevel lev)
180 {
181         m_outputs[lev].push_back(out);
182 }
183
184 void Logger::addOutputMasked(ILogOutput *out, LogLevelMask mask)
185 {
186         for (size_t i = 0; i < LL_MAX; i++) {
187                 if (mask & LOGLEVEL_TO_MASKLEVEL(i))
188                         m_outputs[i].push_back(out);
189         }
190 }
191
192 void Logger::addOutputMaxLevel(ILogOutput *out, LogLevel lev)
193 {
194         assert(lev < LL_MAX);
195         for (size_t i = 0; i <= lev; i++)
196                 m_outputs[i].push_back(out);
197 }
198
199 LogLevelMask Logger::removeOutput(ILogOutput *out)
200 {
201         LogLevelMask ret_mask = 0;
202         for (size_t i = 0; i < LL_MAX; i++) {
203                 std::vector<ILogOutput *>::iterator it;
204
205                 it = std::find(m_outputs[i].begin(), m_outputs[i].end(), out);
206                 if (it != m_outputs[i].end()) {
207                         ret_mask |= LOGLEVEL_TO_MASKLEVEL(i);
208                         m_outputs[i].erase(it);
209                 }
210         }
211         return ret_mask;
212 }
213
214 void Logger::setLevelSilenced(LogLevel lev, bool silenced)
215 {
216         m_silenced_levels[lev] = silenced;
217 }
218
219 void Logger::registerThread(const std::string &name)
220 {
221         threadid_t id = thr_get_current_thread_id();
222         MutexAutoLock lock(m_mutex);
223         m_thread_names[id] = name;
224 }
225
226 void Logger::deregisterThread()
227 {
228         threadid_t id = thr_get_current_thread_id();
229         MutexAutoLock lock(m_mutex);
230         m_thread_names.erase(id);
231 }
232
233 const std::string Logger::getLevelLabel(LogLevel lev)
234 {
235         static const std::string names[] = {
236                 "",
237                 "ERROR",
238                 "WARNING",
239                 "ACTION",
240                 "INFO",
241                 "VERBOSE",
242         };
243         assert(lev < LL_MAX && lev >= 0);
244         STATIC_ASSERT(ARRLEN(names) == LL_MAX,
245                 mismatch_between_loglevel_names_and_enum);
246         return names[lev];
247 }
248
249 const std::string Logger::getThreadName()
250 {
251         std::map<threadid_t, std::string>::const_iterator it;
252
253         threadid_t id = thr_get_current_thread_id();
254         it = m_thread_names.find(id);
255         if (it != m_thread_names.end())
256                 return it->second;
257
258         std::ostringstream os;
259         os << "#0x" << std::hex << id;
260         return os.str();
261 }
262
263 void Logger::log(LogLevel lev, const std::string &text)
264 {
265         if (m_silenced_levels[lev])
266                 return;
267
268         const std::string thread_name = getThreadName();
269         const std::string label = getLevelLabel(lev);
270         const std::string timestamp = getTimestamp();
271         std::ostringstream os(std::ios_base::binary);
272         os << timestamp << ": " << label << "[" << thread_name << "]: " << text;
273
274         logToOutputs(lev, os.str(), timestamp, thread_name, text);
275 }
276
277 void Logger::logRaw(LogLevel lev, const std::string &text)
278 {
279         if (m_silenced_levels[lev])
280                 return;
281
282         logToOutputsRaw(lev, text);
283 }
284
285 void Logger::logToOutputsRaw(LogLevel lev, const std::string &line)
286 {
287         MutexAutoLock lock(m_mutex);
288         for (size_t i = 0; i != m_outputs[lev].size(); i++)
289                 m_outputs[lev][i]->logRaw(lev, line);
290 }
291
292 void Logger::logToOutputs(LogLevel lev, const std::string &combined,
293         const std::string &time, const std::string &thread_name,
294         const std::string &payload_text)
295 {
296         MutexAutoLock lock(m_mutex);
297         for (size_t i = 0; i != m_outputs[lev].size(); i++)
298                 m_outputs[lev][i]->log(lev, combined, time, thread_name, payload_text);
299 }
300
301
302 ////
303 //// *LogOutput methods
304 ////
305
306 void FileLogOutput::open(const std::string &filename)
307 {
308         m_stream.open(filename.c_str(), std::ios::app | std::ios::ate);
309         if (!m_stream.good())
310                 throw FileNotGoodException("Failed to open log file " +
311                         filename + ": " + strerror(errno));
312         m_stream << "\n\n"
313                    "-------------" << std::endl
314                 << "  Separator" << std::endl
315                 << "-------------\n" << std::endl;
316 }
317
318
319
320 ////
321 //// *Buffer methods
322 ////
323
324 int StringBuffer::overflow(int c)
325 {
326         push_back(c);
327         return c;
328 }
329
330
331 std::streamsize StringBuffer::xsputn(const char *s, std::streamsize n)
332 {
333         for (int i = 0; i < n; ++i)
334                 push_back(s[i]);
335         return n;
336 }
337
338 void StringBuffer::push_back(char c)
339 {
340         if (c == '\n' || c == '\r') {
341                 if (!buffer.empty())
342                         flush(buffer);
343                 buffer.clear();
344         } else {
345                 buffer.push_back(c);
346         }
347 }
348
349
350 void LogBuffer::flush(const std::string &buffer)
351 {
352         logger.log(level, buffer);
353 }
354
355 void RawLogBuffer::flush(const std::string &buffer)
356 {
357         g_logger.logRaw(LL_NONE, buffer);
358 }