]> git.lizzy.rs Git - dragonfireclient.git/blob - src/log.cpp
Don't ignore server disconnects in client code
[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 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         m_outputs[lev].push_back(out);
156         m_has_outputs[lev] = true;
157 }
158
159 void Logger::addOutputMasked(ILogOutput *out, LogLevelMask mask)
160 {
161         for (size_t i = 0; i < LL_MAX; i++) {
162                 if (mask & LOGLEVEL_TO_MASKLEVEL(i)) {
163                         m_outputs[i].push_back(out);
164                         m_has_outputs[i] = true;
165                 }
166         }
167 }
168
169 void Logger::addOutputMaxLevel(ILogOutput *out, LogLevel lev)
170 {
171         assert(lev < LL_MAX);
172         for (size_t i = 0; i <= lev; i++) {
173                 m_outputs[i].push_back(out);
174                 m_has_outputs[i] = true;
175         }
176 }
177
178 LogLevelMask Logger::removeOutput(ILogOutput *out)
179 {
180         LogLevelMask ret_mask = 0;
181         for (size_t i = 0; i < LL_MAX; i++) {
182                 std::vector<ILogOutput *>::iterator it;
183
184                 it = std::find(m_outputs[i].begin(), m_outputs[i].end(), out);
185                 if (it != m_outputs[i].end()) {
186                         ret_mask |= LOGLEVEL_TO_MASKLEVEL(i);
187                         m_outputs[i].erase(it);
188                         m_has_outputs[i] = !m_outputs[i].empty();
189                 }
190         }
191         return ret_mask;
192 }
193
194 void Logger::setLevelSilenced(LogLevel lev, bool silenced)
195 {
196         m_silenced_levels[lev] = silenced;
197 }
198
199 void Logger::registerThread(const std::string &name)
200 {
201         std::thread::id id = std::this_thread::get_id();
202         MutexAutoLock lock(m_mutex);
203         m_thread_names[id] = name;
204 }
205
206 void Logger::deregisterThread()
207 {
208         std::thread::id id = std::this_thread::get_id();
209         MutexAutoLock lock(m_mutex);
210         m_thread_names.erase(id);
211 }
212
213 const std::string Logger::getLevelLabel(LogLevel lev)
214 {
215         static const std::string names[] = {
216                 "",
217                 "ERROR",
218                 "WARNING",
219                 "ACTION",
220                 "INFO",
221                 "VERBOSE",
222                 "TRACE",
223         };
224         assert(lev < LL_MAX && lev >= 0);
225         STATIC_ASSERT(ARRLEN(names) == LL_MAX,
226                 mismatch_between_loglevel_names_and_enum);
227         return names[lev];
228 }
229
230 LogColor Logger::color_mode = LOG_COLOR_AUTO;
231
232 const std::string Logger::getThreadName()
233 {
234         std::map<std::thread::id, std::string>::const_iterator it;
235
236         std::thread::id id = std::this_thread::get_id();
237         it = m_thread_names.find(id);
238         if (it != m_thread_names.end())
239                 return it->second;
240
241         std::ostringstream os;
242         os << "#0x" << std::hex << id;
243         return os.str();
244 }
245
246 void Logger::log(LogLevel lev, const std::string &text)
247 {
248         if (m_silenced_levels[lev])
249                 return;
250
251         const std::string thread_name = getThreadName();
252         const std::string label = getLevelLabel(lev);
253         const std::string timestamp = getTimestamp();
254         std::ostringstream os(std::ios_base::binary);
255         os << timestamp << ": " << label << "[" << thread_name << "]: " << text;
256
257         logToOutputs(lev, os.str(), timestamp, thread_name, text);
258 }
259
260 void Logger::logRaw(LogLevel lev, const std::string &text)
261 {
262         if (m_silenced_levels[lev])
263                 return;
264
265         logToOutputsRaw(lev, text);
266 }
267
268 void Logger::logToOutputsRaw(LogLevel lev, const std::string &line)
269 {
270         MutexAutoLock lock(m_mutex);
271         for (size_t i = 0; i != m_outputs[lev].size(); i++)
272                 m_outputs[lev][i]->logRaw(lev, line);
273 }
274
275 void Logger::logToOutputs(LogLevel lev, const std::string &combined,
276         const std::string &time, const std::string &thread_name,
277         const std::string &payload_text)
278 {
279         MutexAutoLock lock(m_mutex);
280         for (size_t i = 0; i != m_outputs[lev].size(); i++)
281                 m_outputs[lev][i]->log(lev, combined, time, thread_name, payload_text);
282 }
283
284 ////
285 //// *LogOutput methods
286 ////
287
288 void FileLogOutput::setFile(const std::string &filename, s64 file_size_max)
289 {
290         // Only move debug.txt if there is a valid maximum file size
291         bool is_too_large = false;
292         if (file_size_max > 0) {
293                 std::ifstream ifile(filename, std::ios::binary | std::ios::ate);
294                 is_too_large = ifile.tellg() > file_size_max;
295                 ifile.close();
296         }
297
298         if (is_too_large) {
299                 std::string filename_secondary = filename + ".1";
300                 actionstream << "The log file grew too big; it is moved to " <<
301                         filename_secondary << std::endl;
302                 remove(filename_secondary.c_str());
303                 rename(filename.c_str(), filename_secondary.c_str());
304         }
305         m_stream.open(filename, std::ios::app | std::ios::ate);
306
307         if (!m_stream.good())
308                 throw FileNotGoodException("Failed to open log file " +
309                         filename + ": " + strerror(errno));
310         m_stream << "\n\n"
311                 "-------------" << std::endl <<
312                 "  Separator" << std::endl <<
313                 "-------------\n" << std::endl;
314 }
315
316 void StreamLogOutput::logRaw(LogLevel lev, const std::string &line)
317 {
318         bool colored_message = (Logger::color_mode == LOG_COLOR_ALWAYS) ||
319                 (Logger::color_mode == LOG_COLOR_AUTO && is_tty);
320         if (colored_message) {
321                 switch (lev) {
322                 case LL_ERROR:
323                         // error is red
324                         m_stream << "\033[91m";
325                         break;
326                 case LL_WARNING:
327                         // warning is yellow
328                         m_stream << "\033[93m";
329                         break;
330                 case LL_INFO:
331                         // info is a bit dark
332                         m_stream << "\033[37m";
333                         break;
334                 case LL_VERBOSE:
335                 case LL_TRACE:
336                         // verbose is darker than info
337                         m_stream << "\033[2m";
338                         break;
339                 default:
340                         // action is white
341                         colored_message = false;
342                 }
343         }
344
345         m_stream << line << std::endl;
346
347         if (colored_message) {
348                 // reset to white color
349                 m_stream << "\033[0m";
350         }
351 }
352
353 void LogOutputBuffer::updateLogLevel()
354 {
355         const std::string &conf_loglev = g_settings->get("chat_log_level");
356         LogLevel log_level = Logger::stringToLevel(conf_loglev);
357         if (log_level == LL_MAX) {
358                 warningstream << "Supplied unrecognized chat_log_level; "
359                         "showing none." << std::endl;
360                 log_level = LL_NONE;
361         }
362
363         m_logger.removeOutput(this);
364         m_logger.addOutputMaxLevel(this, log_level);
365 }
366
367 void LogOutputBuffer::logRaw(LogLevel lev, const std::string &line)
368 {
369         std::string color;
370
371         if (!g_settings->getBool("disable_escape_sequences")) {
372                 switch (lev) {
373                 case LL_ERROR: // red
374                         color = "\x1b(c@#F00)";
375                         break;
376                 case LL_WARNING: // yellow
377                         color = "\x1b(c@#EE0)";
378                         break;
379                 case LL_INFO: // grey
380                         color = "\x1b(c@#BBB)";
381                         break;
382                 case LL_VERBOSE: // dark grey
383                 case LL_TRACE:
384                         color = "\x1b(c@#888)";
385                         break;
386                 default: break;
387                 }
388         }
389
390         m_buffer.push(color.append(line));
391 }