]> git.lizzy.rs Git - minetest.git/blobdiff - src/log.cpp
Use native packer to transfer globals into async env(s)
[minetest.git] / src / log.cpp
index e15bed52acb5bde99f2746a238d5b7143bf04bbc..51652fe0a059eeaa918b6a313e272c489fdd2498 100644 (file)
@@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "debug.h"
 #include "gettime.h"
 #include "porting.h"
+#include "settings.h"
 #include "config.h"
 #include "exceptions.h"
 #include "util/numeric.h"
@@ -34,43 +35,70 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include <cerrno>
 #include <cstring>
 
-class StringBuffer : public std::streambuf {
+class LevelTarget : public LogTarget {
 public:
-       StringBuffer() {}
-
-       int overflow(int c);
-       virtual void flush(const std::string &buf) = 0;
-       std::streamsize xsputn(const char *s, std::streamsize n);
-       void push_back(char c);
-
-private:
-       std::string buffer;
-};
-
-
-class LogBuffer : public StringBuffer {
-public:
-       LogBuffer(Logger &logger, LogLevel lev) :
-               logger(logger),
-               level(lev)
+       LevelTarget(Logger &logger, LogLevel level, bool raw = false) :
+               m_logger(logger),
+               m_level(level),
+               m_raw(raw)
        {}
 
-       void flush(const std::string &buffer);
+       virtual bool hasOutput() override {
+               return m_logger.hasOutput(m_level);
+       }
+
+       virtual void log(const std::string &buf) override {
+               if (!m_raw) {
+                       m_logger.log(m_level, buf);
+               } else {
+                       m_logger.logRaw(m_level, buf);
+               }
+       }
 
 private:
-       Logger &logger;
-       LogLevel level;
+       Logger &m_logger;
+       LogLevel m_level;
+       bool m_raw;
 };
 
+////
+//// Globals
+////
 
-class RawLogBuffer : public StringBuffer {
-public:
-       void flush(const std::string &buffer);
-};
+Logger g_logger;
 
+#ifdef __ANDROID__
+AndroidLogOutput stdout_output;
+AndroidLogOutput stderr_output;
+#else
+StreamLogOutput stdout_output(std::cout);
+StreamLogOutput stderr_output(std::cerr);
+#endif
 
+LevelTarget none_target_raw(g_logger, LL_NONE, true);
+LevelTarget none_target(g_logger, LL_NONE);
+LevelTarget error_target(g_logger, LL_ERROR);
+LevelTarget warning_target(g_logger, LL_WARNING);
+LevelTarget action_target(g_logger, LL_ACTION);
+LevelTarget info_target(g_logger, LL_INFO);
+LevelTarget verbose_target(g_logger, LL_VERBOSE);
+LevelTarget trace_target(g_logger, LL_TRACE);
+
+thread_local LogStream dstream(none_target);
+thread_local LogStream rawstream(none_target_raw);
+thread_local LogStream errorstream(error_target);
+thread_local LogStream warningstream(warning_target);
+thread_local LogStream actionstream(action_target);
+thread_local LogStream infostream(info_target);
+thread_local LogStream verbosestream(verbose_target);
+thread_local LogStream tracestream(trace_target);
+thread_local LogStream derr_con(verbose_target);
+thread_local LogStream dout_con(trace_target);
+
+// Android
 #ifdef __ANDROID__
-static unsigned int level_to_android[] = {
+
+static unsigned int g_level_to_android[] = {
        ANDROID_LOG_INFO,     // LL_NONE
        //ANDROID_LOG_FATAL,
        ANDROID_LOG_ERROR,    // LL_ERROR
@@ -79,52 +107,17 @@ static unsigned int level_to_android[] = {
        //ANDROID_LOG_INFO,
        ANDROID_LOG_DEBUG,    // LL_INFO
        ANDROID_LOG_VERBOSE,  // LL_VERBOSE
-
+       ANDROID_LOG_VERBOSE,  // LL_TRACE
 };
-#endif
-
-////
-//// Globals
-////
-
-Logger g_logger;
-
-StreamLogOutput stdout_output(std::cout);
-StreamLogOutput stderr_output(std::cerr);
-std::ostream null_stream(NULL);
-
-RawLogBuffer raw_buf;
-
-LogBuffer none_buf(g_logger, LL_NONE);
-LogBuffer error_buf(g_logger, LL_ERROR);
-LogBuffer warning_buf(g_logger, LL_WARNING);
-LogBuffer action_buf(g_logger, LL_ACTION);
-LogBuffer info_buf(g_logger, LL_INFO);
-LogBuffer verbose_buf(g_logger, LL_VERBOSE);
-
-// Connection
-std::ostream *dout_con_ptr = &null_stream;
-std::ostream *derr_con_ptr = &verbosestream;
-
-// Server
-std::ostream *dout_server_ptr = &infostream;
-std::ostream *derr_server_ptr = &errorstream;
 
-#ifndef SERVER
-// Client
-std::ostream *dout_client_ptr = &infostream;
-std::ostream *derr_client_ptr = &errorstream;
+void AndroidLogOutput::logRaw(LogLevel lev, const std::string &line) {
+       STATIC_ASSERT(ARRLEN(g_level_to_android) == LL_MAX,
+               mismatch_between_android_and_internal_loglevels);
+       __android_log_print(g_level_to_android[lev],
+               PROJECT_NAME_C, "%s", line.c_str());
+}
 #endif
 
-std::ostream rawstream(&raw_buf);
-std::ostream dstream(&none_buf);
-std::ostream errorstream(&error_buf);
-std::ostream warningstream(&warning_buf);
-std::ostream actionstream(&action_buf);
-std::ostream infostream(&info_buf);
-std::ostream verbosestream(&verbose_buf);
-
-
 ///////////////////////////////////////////////////////////////////////////////
 
 
@@ -146,35 +139,56 @@ LogLevel Logger::stringToLevel(const std::string &name)
                return LL_INFO;
        else if (name == "verbose")
                return LL_VERBOSE;
+       else if (name == "trace")
+               return LL_TRACE;
        else
                return LL_MAX;
 }
 
 void Logger::addOutput(ILogOutput *out)
 {
-       addOutputMaxLevel(out, LL_MAX);
+       addOutputMaxLevel(out, (LogLevel)(LL_MAX - 1));
 }
 
 void Logger::addOutput(ILogOutput *out, LogLevel lev)
 {
        m_outputs[lev].push_back(out);
+       m_has_outputs[lev] = true;
+}
+
+void Logger::addOutputMasked(ILogOutput *out, LogLevelMask mask)
+{
+       for (size_t i = 0; i < LL_MAX; i++) {
+               if (mask & LOGLEVEL_TO_MASKLEVEL(i)) {
+                       m_outputs[i].push_back(out);
+                       m_has_outputs[i] = true;
+               }
+       }
 }
 
 void Logger::addOutputMaxLevel(ILogOutput *out, LogLevel lev)
 {
-       for (size_t i = 0; i <= lev; i++)
+       assert(lev < LL_MAX);
+       for (size_t i = 0; i <= lev; i++) {
                m_outputs[i].push_back(out);
+               m_has_outputs[i] = true;
+       }
 }
 
-void Logger::removeOutput(ILogOutput *out)
+LogLevelMask Logger::removeOutput(ILogOutput *out)
 {
+       LogLevelMask ret_mask = 0;
        for (size_t i = 0; i < LL_MAX; i++) {
                std::vector<ILogOutput *>::iterator it;
 
                it = std::find(m_outputs[i].begin(), m_outputs[i].end(), out);
-               if (it != m_outputs[i].end())
+               if (it != m_outputs[i].end()) {
+                       ret_mask |= LOGLEVEL_TO_MASKLEVEL(i);
                        m_outputs[i].erase(it);
+                       m_has_outputs[i] = !m_outputs[i].empty();
+               }
        }
+       return ret_mask;
 }
 
 void Logger::setLevelSilenced(LogLevel lev, bool silenced)
@@ -184,14 +198,14 @@ void Logger::setLevelSilenced(LogLevel lev, bool silenced)
 
 void Logger::registerThread(const std::string &name)
 {
-       threadid_t id = thr_get_current_thread_id();
+       std::thread::id id = std::this_thread::get_id();
        MutexAutoLock lock(m_mutex);
        m_thread_names[id] = name;
 }
 
 void Logger::deregisterThread()
 {
-       threadid_t id = thr_get_current_thread_id();
+       std::thread::id id = std::this_thread::get_id();
        MutexAutoLock lock(m_mutex);
        m_thread_names.erase(id);
 }
@@ -205,17 +219,21 @@ const std::string Logger::getLevelLabel(LogLevel lev)
                "ACTION",
                "INFO",
                "VERBOSE",
+               "TRACE",
        };
        assert(lev < LL_MAX && lev >= 0);
-       assert(ARRLEN(names) == LL_MAX);
+       STATIC_ASSERT(ARRLEN(names) == LL_MAX,
+               mismatch_between_loglevel_names_and_enum);
        return names[lev];
 }
 
+LogColor Logger::color_mode = LOG_COLOR_AUTO;
+
 const std::string Logger::getThreadName()
 {
-       std::map<threadid_t, std::string>::const_iterator it;
+       std::map<std::thread::id, std::string>::const_iterator it;
 
-       threadid_t id = thr_get_current_thread_id();
+       std::thread::id id = std::this_thread::get_id();
        it = m_thread_names.find(id);
        if (it != m_thread_names.end())
                return it->second;
@@ -232,11 +250,11 @@ void Logger::log(LogLevel lev, const std::string &text)
 
        const std::string thread_name = getThreadName();
        const std::string label = getLevelLabel(lev);
+       const std::string timestamp = getTimestamp();
        std::ostringstream os(std::ios_base::binary);
-       os << getTimestamp() << ": " << label << "[" << thread_name << "]: " << text;
+       os << timestamp << ": " << label << "[" << thread_name << "]: " << text;
 
-       logToSystem(lev, text);
-       logToOutputs(lev, os.str());
+       logToOutputs(lev, os.str(), timestamp, thread_name, text);
 }
 
 void Logger::logRaw(LogLevel lev, const std::string &text)
@@ -244,83 +262,130 @@ void Logger::logRaw(LogLevel lev, const std::string &text)
        if (m_silenced_levels[lev])
                return;
 
-       logToSystem(lev, text);
-       logToOutputs(lev, text);
+       logToOutputsRaw(lev, text);
 }
 
-void Logger::logToSystem(LogLevel lev, const std::string &text)
+void Logger::logToOutputsRaw(LogLevel lev, const std::string &line)
 {
-#ifdef __ANDROID__
-       assert(ARRLEN(level_to_android) == LL_MAX);
-       __android_log_print(level_to_android[lev],
-               PROJECT_NAME_C, "%s", text.c_str());
-#endif
+       MutexAutoLock lock(m_mutex);
+       for (size_t i = 0; i != m_outputs[lev].size(); i++)
+               m_outputs[lev][i]->logRaw(lev, line);
 }
 
-void Logger::logToOutputs(LogLevel lev, const std::string &text)
+void Logger::logToOutputs(LogLevel lev, const std::string &combined,
+       const std::string &time, const std::string &thread_name,
+       const std::string &payload_text)
 {
        MutexAutoLock lock(m_mutex);
        for (size_t i = 0; i != m_outputs[lev].size(); i++)
-               m_outputs[lev][i]->log(text);
+               m_outputs[lev][i]->log(lev, combined, time, thread_name, payload_text);
 }
 
-
 ////
 //// *LogOutput methods
 ////
 
-void FileLogOutput::open(const std::string &filename)
+void FileLogOutput::setFile(const std::string &filename, s64 file_size_max)
 {
-       stream.open(filename.c_str(), std::ios::app | std::ios::ate);
-       if (!stream.good())
+       // Only move debug.txt if there is a valid maximum file size
+       bool is_too_large = false;
+       if (file_size_max > 0) {
+               std::ifstream ifile(filename, std::ios::binary | std::ios::ate);
+               is_too_large = ifile.tellg() > file_size_max;
+               ifile.close();
+       }
+
+       if (is_too_large) {
+               std::string filename_secondary = filename + ".1";
+               actionstream << "The log file grew too big; it is moved to " <<
+                       filename_secondary << std::endl;
+               remove(filename_secondary.c_str());
+               rename(filename.c_str(), filename_secondary.c_str());
+       }
+       m_stream.open(filename, std::ios::app | std::ios::ate);
+
+       if (!m_stream.good())
                throw FileNotGoodException("Failed to open log file " +
                        filename + ": " + strerror(errno));
-       stream << "\n\n"
-                  "-------------" << std::endl
-               << "  Separator" << std::endl
-               << "-------------\n" << std::endl;
+       m_stream << "\n\n"
+               "-------------" << std::endl <<
+               "  Separator" << std::endl <<
+               "-------------\n" << std::endl;
 }
 
-
-
-////
-//// *Buffer methods
-////
-
-int StringBuffer::overflow(int c)
+void StreamLogOutput::logRaw(LogLevel lev, const std::string &line)
 {
-       push_back(c);
-       return c;
-}
+       bool colored_message = (Logger::color_mode == LOG_COLOR_ALWAYS) ||
+               (Logger::color_mode == LOG_COLOR_AUTO && is_tty);
+       if (colored_message) {
+               switch (lev) {
+               case LL_ERROR:
+                       // error is red
+                       m_stream << "\033[91m";
+                       break;
+               case LL_WARNING:
+                       // warning is yellow
+                       m_stream << "\033[93m";
+                       break;
+               case LL_INFO:
+                       // info is a bit dark
+                       m_stream << "\033[37m";
+                       break;
+               case LL_VERBOSE:
+               case LL_TRACE:
+                       // verbose is darker than info
+                       m_stream << "\033[2m";
+                       break;
+               default:
+                       // action is white
+                       colored_message = false;
+               }
+       }
 
+       m_stream << line << std::endl;
 
-std::streamsize StringBuffer::xsputn(const char *s, std::streamsize n)
-{
-       for (int i = 0; i < n; ++i)
-               push_back(s[i]);
-       return n;
+       if (colored_message) {
+               // reset to white color
+               m_stream << "\033[0m";
+       }
 }
 
-void StringBuffer::push_back(char c)
+void LogOutputBuffer::updateLogLevel()
 {
-       if (c == '\n' || c == '\r') {
-               if (!buffer.empty())
-                       flush(buffer);
-               buffer.clear();
-       } else {
-               buffer.push_back(c);
+       const std::string &conf_loglev = g_settings->get("chat_log_level");
+       LogLevel log_level = Logger::stringToLevel(conf_loglev);
+       if (log_level == LL_MAX) {
+               warningstream << "Supplied unrecognized chat_log_level; "
+                       "showing none." << std::endl;
+               log_level = LL_NONE;
        }
-}
-
-
 
-
-void LogBuffer::flush(const std::string &buffer)
-{
-       logger.log(level, buffer);
+       m_logger.removeOutput(this);
+       m_logger.addOutputMaxLevel(this, log_level);
 }
 
-void RawLogBuffer::flush(const std::string &buffer)
+void LogOutputBuffer::logRaw(LogLevel lev, const std::string &line)
 {
-       g_logger.logRaw(LL_NONE, buffer);
+       std::string color;
+
+       if (!g_settings->getBool("disable_escape_sequences")) {
+               switch (lev) {
+               case LL_ERROR: // red
+                       color = "\x1b(c@#F00)";
+                       break;
+               case LL_WARNING: // yellow
+                       color = "\x1b(c@#EE0)";
+                       break;
+               case LL_INFO: // grey
+                       color = "\x1b(c@#BBB)";
+                       break;
+               case LL_VERBOSE: // dark grey
+               case LL_TRACE:
+                       color = "\x1b(c@#888)";
+                       break;
+               default: break;
+               }
+       }
+
+       m_buffer.push(color.append(line));
 }