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