wasplib: add inv management helpers
[waspsaliva.git] / src / log.cpp
blob3c61414e901c57e1626104d3c0e0df55b79be347
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
20 #include "log.h"
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"
32 #include <sstream>
33 #include <iostream>
34 #include <algorithm>
35 #include <cerrno>
36 #include <cstring>
38 const int BUFFER_LENGTH = 256;
40 class StringBuffer : public std::streambuf {
41 public:
42 StringBuffer() {
43 buffer_index = 0;
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);
51 private:
52 char buffer[BUFFER_LENGTH];
53 int buffer_index;
57 class LogBuffer : public StringBuffer {
58 public:
59 LogBuffer(Logger &logger, LogLevel lev) :
60 logger(logger),
61 level(lev)
64 void flush(const std::string &buffer);
66 private:
67 Logger &logger;
68 LogLevel level;
72 class RawLogBuffer : public StringBuffer {
73 public:
74 void flush(const std::string &buffer);
77 ////
78 //// Globals
79 ////
81 Logger g_logger;
83 StreamLogOutput stdout_output(std::cout);
84 StreamLogOutput stderr_output(std::cerr);
85 std::ostream null_stream(NULL);
87 RawLogBuffer raw_buf;
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);
96 // Connection
97 std::ostream *dout_con_ptr = &null_stream;
98 std::ostream *derr_con_ptr = &verbosestream;
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);
109 // Android
110 #ifdef __ANDROID__
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
123 class AndroidSystemLogOutput : public ICombinedLogOutput {
124 public:
125 AndroidSystemLogOutput()
127 g_logger.addOutput(this);
129 ~AndroidSystemLogOutput()
131 g_logger.removeOutput(this);
133 void logRaw(LogLevel lev, const std::string &line)
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());
142 AndroidSystemLogOutput g_android_log_output;
144 #endif
146 ///////////////////////////////////////////////////////////////////////////////
149 ////
150 //// Logger
151 ////
153 LogLevel Logger::stringToLevel(const std::string &name)
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;
171 void Logger::addOutput(ILogOutput *out)
173 addOutputMaxLevel(out, (LogLevel)(LL_MAX - 1));
176 void Logger::addOutput(ILogOutput *out, LogLevel lev)
178 m_outputs[lev].push_back(out);
181 void Logger::addOutputMasked(ILogOutput *out, LogLevelMask mask)
183 for (size_t i = 0; i < LL_MAX; i++) {
184 if (mask & LOGLEVEL_TO_MASKLEVEL(i))
185 m_outputs[i].push_back(out);
189 void Logger::addOutputMaxLevel(ILogOutput *out, LogLevel lev)
191 assert(lev < LL_MAX);
192 for (size_t i = 0; i <= lev; i++)
193 m_outputs[i].push_back(out);
196 LogLevelMask Logger::removeOutput(ILogOutput *out)
198 LogLevelMask ret_mask = 0;
199 for (size_t i = 0; i < LL_MAX; i++) {
200 std::vector<ILogOutput *>::iterator it;
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);
208 return ret_mask;
211 void Logger::setLevelSilenced(LogLevel lev, bool silenced)
213 m_silenced_levels[lev] = silenced;
216 void Logger::registerThread(const std::string &name)
218 std::thread::id id = std::this_thread::get_id();
219 MutexAutoLock lock(m_mutex);
220 m_thread_names[id] = name;
223 void Logger::deregisterThread()
225 std::thread::id id = std::this_thread::get_id();
226 MutexAutoLock lock(m_mutex);
227 m_thread_names.erase(id);
230 const std::string Logger::getLevelLabel(LogLevel lev)
232 static const std::string names[] = {
234 "ERROR",
235 "WARNING",
236 "ACTION",
237 "INFO",
238 "VERBOSE",
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];
246 LogColor Logger::color_mode = LOG_COLOR_AUTO;
248 const std::string Logger::getThreadName()
250 std::map<std::thread::id, std::string>::const_iterator it;
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;
257 std::ostringstream os;
258 os << "#0x" << std::hex << id;
259 return os.str();
262 void Logger::log(LogLevel lev, const std::string &text)
264 if (m_silenced_levels[lev])
265 return;
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;
273 logToOutputs(lev, os.str(), timestamp, thread_name, text);
276 void Logger::logRaw(LogLevel lev, const std::string &text)
278 if (m_silenced_levels[lev])
279 return;
281 logToOutputsRaw(lev, text);
284 void Logger::logToOutputsRaw(LogLevel lev, const std::string &line)
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);
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)
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);
301 ////
302 //// *LogOutput methods
303 ////
305 void FileLogOutput::setFile(const std::string &filename, s64 file_size_max)
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();
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());
322 m_stream.open(filename, std::ios::app | std::ios::ate);
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;
333 void StreamLogOutput::logRaw(LogLevel lev, const std::string &line)
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;
361 m_stream << line << std::endl;
363 if (colored_message) {
364 // reset to white color
365 m_stream << "\033[0m";
369 void LogOutputBuffer::updateLogLevel()
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;
379 m_logger.removeOutput(this);
380 m_logger.addOutputMaxLevel(this, log_level);
383 void LogOutputBuffer::logRaw(LogLevel lev, const std::string &line)
385 std::string color;
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;
405 m_buffer.push(color.append(line));
408 ////
409 //// *Buffer methods
410 ////
412 int StringBuffer::overflow(int c)
414 push_back(c);
415 return c;
419 std::streamsize StringBuffer::xsputn(const char *s, std::streamsize n)
421 for (int i = 0; i < n; ++i)
422 push_back(s[i]);
423 return n;
426 void StringBuffer::push_back(char c)
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;
442 void LogBuffer::flush(const std::string &buffer)
444 logger.log(level, buffer);
447 void RawLogBuffer::flush(const std::string &buffer)
449 g_logger.logRaw(LL_NONE, buffer);