]> git.lizzy.rs Git - dragonfireclient.git/blob - src/log.cpp
Merge branch 'master' of https://github.com/EliasFleckenstein03/dragonfireclient
[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 "settings.h"
27 #include "config.h"
28 #include "exceptions.h"
29 #include "util/numeric.h"
30 #include "log.h"
31
32 #include <sstream>
33 #include <iostream>
34 #include <algorithm>
35 #include <cerrno>
36 #include <cstring>
37
38 const int BUFFER_LENGTH = 256;
39
40 class StringBuffer : public std::streambuf {
41 public:
42         StringBuffer() {
43                 buffer_index = 0;
44         }
45
46         int overflow(int c);
47         virtual void flush(const std::string &buf) = 0;
48         std::streamsize xsputn(const char *s, std::streamsize n);
49         void push_back(char c);
50
51 private:
52         char buffer[BUFFER_LENGTH];
53         int buffer_index;
54 };
55
56
57 class LogBuffer : public StringBuffer {
58 public:
59         LogBuffer(Logger &logger, LogLevel lev) :
60                 logger(logger),
61                 level(lev)
62         {}
63
64         void flush(const std::string &buffer);
65
66 private:
67         Logger &logger;
68         LogLevel level;
69 };
70
71
72 class RawLogBuffer : public StringBuffer {
73 public:
74         void flush(const std::string &buffer);
75 };
76
77 ////
78 //// Globals
79 ////
80
81 Logger g_logger;
82
83 StreamLogOutput stdout_output(std::cout);
84 StreamLogOutput stderr_output(std::cerr);
85 std::ostream null_stream(NULL);
86
87 RawLogBuffer raw_buf;
88
89 LogBuffer none_buf(g_logger, LL_NONE);
90 LogBuffer error_buf(g_logger, LL_ERROR);
91 LogBuffer warning_buf(g_logger, LL_WARNING);
92 LogBuffer action_buf(g_logger, LL_ACTION);
93 LogBuffer info_buf(g_logger, LL_INFO);
94 LogBuffer verbose_buf(g_logger, LL_VERBOSE);
95
96 // Connection
97 std::ostream *dout_con_ptr = &null_stream;
98 std::ostream *derr_con_ptr = &verbosestream;
99
100 // Common streams
101 std::ostream rawstream(&raw_buf);
102 std::ostream dstream(&none_buf);
103 std::ostream errorstream(&error_buf);
104 std::ostream warningstream(&warning_buf);
105 std::ostream actionstream(&action_buf);
106 std::ostream infostream(&info_buf);
107 std::ostream verbosestream(&verbose_buf);
108
109 // Android
110 #ifdef __ANDROID__
111
112 static unsigned int g_level_to_android[] = {
113         ANDROID_LOG_INFO,     // LL_NONE
114         //ANDROID_LOG_FATAL,
115         ANDROID_LOG_ERROR,    // LL_ERROR
116         ANDROID_LOG_WARN,     // LL_WARNING
117         ANDROID_LOG_WARN,     // LL_ACTION
118         //ANDROID_LOG_INFO,
119         ANDROID_LOG_DEBUG,    // LL_INFO
120         ANDROID_LOG_VERBOSE,  // LL_VERBOSE
121 };
122
123 class AndroidSystemLogOutput : public ICombinedLogOutput {
124         public:
125                 AndroidSystemLogOutput()
126                 {
127                         g_logger.addOutput(this);
128                 }
129                 ~AndroidSystemLogOutput()
130                 {
131                         g_logger.removeOutput(this);
132                 }
133                 void logRaw(LogLevel lev, const std::string &line)
134                 {
135                         STATIC_ASSERT(ARRLEN(g_level_to_android) == LL_MAX,
136                                 mismatch_between_android_and_internal_loglevels);
137                         __android_log_print(g_level_to_android[lev],
138                                 PROJECT_NAME_C, "%s", line.c_str());
139                 }
140 };
141
142 AndroidSystemLogOutput g_android_log_output;
143
144 #endif
145
146 ///////////////////////////////////////////////////////////////////////////////
147
148
149 ////
150 //// Logger
151 ////
152
153 LogLevel Logger::stringToLevel(const std::string &name)
154 {
155         if (name == "none")
156                 return LL_NONE;
157         else if (name == "error")
158                 return LL_ERROR;
159         else if (name == "warning")
160                 return LL_WARNING;
161         else if (name == "action")
162                 return LL_ACTION;
163         else if (name == "info")
164                 return LL_INFO;
165         else if (name == "verbose")
166                 return LL_VERBOSE;
167         else
168                 return LL_MAX;
169 }
170
171 void Logger::addOutput(ILogOutput *out)
172 {
173         addOutputMaxLevel(out, (LogLevel)(LL_MAX - 1));
174 }
175
176 void Logger::addOutput(ILogOutput *out, LogLevel lev)
177 {
178         m_outputs[lev].push_back(out);
179 }
180
181 void Logger::addOutputMasked(ILogOutput *out, LogLevelMask mask)
182 {
183         for (size_t i = 0; i < LL_MAX; i++) {
184                 if (mask & LOGLEVEL_TO_MASKLEVEL(i))
185                         m_outputs[i].push_back(out);
186         }
187 }
188
189 void Logger::addOutputMaxLevel(ILogOutput *out, LogLevel lev)
190 {
191         assert(lev < LL_MAX);
192         for (size_t i = 0; i <= lev; i++)
193                 m_outputs[i].push_back(out);
194 }
195
196 LogLevelMask Logger::removeOutput(ILogOutput *out)
197 {
198         LogLevelMask ret_mask = 0;
199         for (size_t i = 0; i < LL_MAX; i++) {
200                 std::vector<ILogOutput *>::iterator it;
201
202                 it = std::find(m_outputs[i].begin(), m_outputs[i].end(), out);
203                 if (it != m_outputs[i].end()) {
204                         ret_mask |= LOGLEVEL_TO_MASKLEVEL(i);
205                         m_outputs[i].erase(it);
206                 }
207         }
208         return ret_mask;
209 }
210
211 void Logger::setLevelSilenced(LogLevel lev, bool silenced)
212 {
213         m_silenced_levels[lev] = silenced;
214 }
215
216 void Logger::registerThread(const std::string &name)
217 {
218         std::thread::id id = std::this_thread::get_id();
219         MutexAutoLock lock(m_mutex);
220         m_thread_names[id] = name;
221 }
222
223 void Logger::deregisterThread()
224 {
225         std::thread::id id = std::this_thread::get_id();
226         MutexAutoLock lock(m_mutex);
227         m_thread_names.erase(id);
228 }
229
230 const std::string Logger::getLevelLabel(LogLevel lev)
231 {
232         static const std::string names[] = {
233                 "",
234                 "ERROR",
235                 "WARNING",
236                 "ACTION",
237                 "INFO",
238                 "VERBOSE",
239         };
240         assert(lev < LL_MAX && lev >= 0);
241         STATIC_ASSERT(ARRLEN(names) == LL_MAX,
242                 mismatch_between_loglevel_names_and_enum);
243         return names[lev];
244 }
245
246 LogColor Logger::color_mode = LOG_COLOR_AUTO;
247
248 const std::string Logger::getThreadName()
249 {
250         std::map<std::thread::id, std::string>::const_iterator it;
251
252         std::thread::id id = std::this_thread::get_id();
253         it = m_thread_names.find(id);
254         if (it != m_thread_names.end())
255                 return it->second;
256
257         std::ostringstream os;
258         os << "#0x" << std::hex << id;
259         return os.str();
260 }
261
262 void Logger::log(LogLevel lev, const std::string &text)
263 {
264         if (m_silenced_levels[lev])
265                 return;
266
267         const std::string thread_name = getThreadName();
268         const std::string label = getLevelLabel(lev);
269         const std::string timestamp = getTimestamp();
270         std::ostringstream os(std::ios_base::binary);
271         os << timestamp << ": " << label << "[" << thread_name << "]: " << text;
272
273         logToOutputs(lev, os.str(), timestamp, thread_name, text);
274 }
275
276 void Logger::logRaw(LogLevel lev, const std::string &text)
277 {
278         if (m_silenced_levels[lev])
279                 return;
280
281         logToOutputsRaw(lev, text);
282 }
283
284 void Logger::logToOutputsRaw(LogLevel lev, const std::string &line)
285 {
286         MutexAutoLock lock(m_mutex);
287         for (size_t i = 0; i != m_outputs[lev].size(); i++)
288                 m_outputs[lev][i]->logRaw(lev, line);
289 }
290
291 void Logger::logToOutputs(LogLevel lev, const std::string &combined,
292         const std::string &time, const std::string &thread_name,
293         const std::string &payload_text)
294 {
295         MutexAutoLock lock(m_mutex);
296         for (size_t i = 0; i != m_outputs[lev].size(); i++)
297                 m_outputs[lev][i]->log(lev, combined, time, thread_name, payload_text);
298 }
299
300
301 ////
302 //// *LogOutput methods
303 ////
304
305 void FileLogOutput::setFile(const std::string &filename, s64 file_size_max)
306 {
307         // Only move debug.txt if there is a valid maximum file size
308         bool is_too_large = false;
309         if (file_size_max > 0) {
310                 std::ifstream ifile(filename, std::ios::binary | std::ios::ate);
311                 is_too_large = ifile.tellg() > file_size_max;
312                 ifile.close();
313         }
314
315         if (is_too_large) {
316                 std::string filename_secondary = filename + ".1";
317                 actionstream << "The log file grew too big; it is moved to " <<
318                         filename_secondary << std::endl;
319                 remove(filename_secondary.c_str());
320                 rename(filename.c_str(), filename_secondary.c_str());
321         }
322         m_stream.open(filename, std::ios::app | std::ios::ate);
323
324         if (!m_stream.good())
325                 throw FileNotGoodException("Failed to open log file " +
326                         filename + ": " + strerror(errno));
327         m_stream << "\n\n"
328                 "-------------" << std::endl <<
329                 "  Separator" << std::endl <<
330                 "-------------\n" << std::endl;
331 }
332
333 void StreamLogOutput::logRaw(LogLevel lev, const std::string &line)
334 {
335         bool colored_message = (Logger::color_mode == LOG_COLOR_ALWAYS) ||
336                 (Logger::color_mode == LOG_COLOR_AUTO && is_tty);
337         if (colored_message) {
338                 switch (lev) {
339                 case LL_ERROR:
340                         // error is red
341                         m_stream << "\033[91m";
342                         break;
343                 case LL_WARNING:
344                         // warning is yellow
345                         m_stream << "\033[93m";
346                         break;
347                 case LL_INFO:
348                         // info is a bit dark
349                         m_stream << "\033[37m";
350                         break;
351                 case LL_VERBOSE:
352                         // verbose is darker than info
353                         m_stream << "\033[2m";
354                         break;
355                 default:
356                         // action is white
357                         colored_message = false;
358                 }
359         }
360
361         m_stream << line << std::endl;
362
363         if (colored_message) {
364                 // reset to white color
365                 m_stream << "\033[0m";
366         }
367 }
368
369 void LogOutputBuffer::updateLogLevel()
370 {
371         const std::string &conf_loglev = g_settings->get("chat_log_level");
372         LogLevel log_level = Logger::stringToLevel(conf_loglev);
373         if (log_level == LL_MAX) {
374                 warningstream << "Supplied unrecognized chat_log_level; "
375                         "showing none." << std::endl;
376                 log_level = LL_NONE;
377         }
378
379         m_logger.removeOutput(this);
380         m_logger.addOutputMaxLevel(this, log_level);
381 }
382
383 void LogOutputBuffer::logRaw(LogLevel lev, const std::string &line)
384 {
385         std::string color;
386
387         if (!g_settings->getBool("disable_escape_sequences")) {
388                 switch (lev) {
389                 case LL_ERROR: // red
390                         color = "\x1b(c@#F00)";
391                         break;
392                 case LL_WARNING: // yellow
393                         color = "\x1b(c@#EE0)";
394                         break;
395                 case LL_INFO: // grey
396                         color = "\x1b(c@#BBB)";
397                         break;
398                 case LL_VERBOSE: // dark grey
399                         color = "\x1b(c@#888)";
400                         break;
401                 default: break;
402                 }
403         }
404
405         m_buffer.push(color.append(line));
406 }
407
408 ////
409 //// *Buffer methods
410 ////
411
412 int StringBuffer::overflow(int c)
413 {
414         push_back(c);
415         return c;
416 }
417
418
419 std::streamsize StringBuffer::xsputn(const char *s, std::streamsize n)
420 {
421         for (int i = 0; i < n; ++i)
422                 push_back(s[i]);
423         return n;
424 }
425
426 void StringBuffer::push_back(char c)
427 {
428         if (c == '\n' || c == '\r') {
429                 if (buffer_index)
430                         flush(std::string(buffer, buffer_index));
431                 buffer_index = 0;
432         } else {
433                 buffer[buffer_index++] = c;
434                 if (buffer_index >= BUFFER_LENGTH) {
435                         flush(std::string(buffer, buffer_index));
436                         buffer_index = 0;
437                 }
438         }
439 }
440
441
442 void LogBuffer::flush(const std::string &buffer)
443 {
444         logger.log(level, buffer);
445 }
446
447 void RawLogBuffer::flush(const std::string &buffer)
448 {
449         g_logger.logRaw(LL_NONE, buffer);
450 }