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