log.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "log.h"
  17. #include "threading/mutex_auto_lock.h"
  18. #include "debug.h"
  19. #include "gettime.h"
  20. #include "porting.h"
  21. #include "settings.h"
  22. #include "config.h"
  23. #include "exceptions.h"
  24. #include "util/numeric.h"
  25. #include "log.h"
  26. #include <sstream>
  27. #include <iostream>
  28. #include <algorithm>
  29. #include <cerrno>
  30. #include <cstring>
  31. class LevelTarget : public LogTarget {
  32. public:
  33. LevelTarget(Logger &logger, LogLevel level, bool raw = false) :
  34. m_logger(logger),
  35. m_level(level),
  36. m_raw(raw)
  37. {}
  38. virtual bool hasOutput() override {
  39. return m_logger.hasOutput(m_level);
  40. }
  41. virtual void log(const std::string &buf) override {
  42. if (!m_raw) {
  43. m_logger.log(m_level, buf);
  44. } else {
  45. m_logger.logRaw(m_level, buf);
  46. }
  47. }
  48. private:
  49. Logger &m_logger;
  50. LogLevel m_level;
  51. bool m_raw;
  52. };
  53. ////
  54. //// Globals
  55. ////
  56. Logger g_logger;
  57. #ifdef __ANDROID__
  58. AndroidLogOutput stdout_output;
  59. AndroidLogOutput stderr_output;
  60. #else
  61. StreamLogOutput stdout_output(std::cout);
  62. StreamLogOutput stderr_output(std::cerr);
  63. #endif
  64. LevelTarget none_target_raw(g_logger, LL_NONE, true);
  65. LevelTarget none_target(g_logger, LL_NONE);
  66. LevelTarget error_target(g_logger, LL_ERROR);
  67. LevelTarget warning_target(g_logger, LL_WARNING);
  68. LevelTarget action_target(g_logger, LL_ACTION);
  69. LevelTarget info_target(g_logger, LL_INFO);
  70. LevelTarget verbose_target(g_logger, LL_VERBOSE);
  71. LevelTarget trace_target(g_logger, LL_TRACE);
  72. thread_local LogStream dstream(none_target);
  73. thread_local LogStream rawstream(none_target_raw);
  74. thread_local LogStream errorstream(error_target);
  75. thread_local LogStream warningstream(warning_target);
  76. thread_local LogStream actionstream(action_target);
  77. thread_local LogStream infostream(info_target);
  78. thread_local LogStream verbosestream(verbose_target);
  79. thread_local LogStream tracestream(trace_target);
  80. thread_local LogStream derr_con(verbose_target);
  81. thread_local LogStream dout_con(trace_target);
  82. // Android
  83. #ifdef __ANDROID__
  84. static unsigned int g_level_to_android[] = {
  85. ANDROID_LOG_INFO, // LL_NONE
  86. //ANDROID_LOG_FATAL,
  87. ANDROID_LOG_ERROR, // LL_ERROR
  88. ANDROID_LOG_WARN, // LL_WARNING
  89. ANDROID_LOG_WARN, // LL_ACTION
  90. //ANDROID_LOG_INFO,
  91. ANDROID_LOG_DEBUG, // LL_INFO
  92. ANDROID_LOG_VERBOSE, // LL_VERBOSE
  93. ANDROID_LOG_VERBOSE, // LL_TRACE
  94. };
  95. void AndroidLogOutput::logRaw(LogLevel lev, const std::string &line) {
  96. STATIC_ASSERT(ARRLEN(g_level_to_android) == LL_MAX,
  97. mismatch_between_android_and_internal_loglevels);
  98. __android_log_print(g_level_to_android[lev],
  99. PROJECT_NAME_C, "%s", line.c_str());
  100. }
  101. #endif
  102. ///////////////////////////////////////////////////////////////////////////////
  103. ////
  104. //// Logger
  105. ////
  106. LogLevel Logger::stringToLevel(const std::string &name)
  107. {
  108. if (name == "none")
  109. return LL_NONE;
  110. else if (name == "error")
  111. return LL_ERROR;
  112. else if (name == "warning")
  113. return LL_WARNING;
  114. else if (name == "action")
  115. return LL_ACTION;
  116. else if (name == "info")
  117. return LL_INFO;
  118. else if (name == "verbose")
  119. return LL_VERBOSE;
  120. else if (name == "trace")
  121. return LL_TRACE;
  122. else
  123. return LL_MAX;
  124. }
  125. void Logger::addOutput(ILogOutput *out)
  126. {
  127. addOutputMaxLevel(out, (LogLevel)(LL_MAX - 1));
  128. }
  129. void Logger::addOutput(ILogOutput *out, LogLevel lev)
  130. {
  131. MutexAutoLock lock(m_mutex);
  132. m_outputs[lev].push_back(out);
  133. m_has_outputs[lev] = true;
  134. }
  135. void Logger::addOutputMasked(ILogOutput *out, LogLevelMask mask)
  136. {
  137. MutexAutoLock lock(m_mutex);
  138. for (size_t i = 0; i < LL_MAX; i++) {
  139. if (mask & LOGLEVEL_TO_MASKLEVEL(i)) {
  140. m_outputs[i].push_back(out);
  141. m_has_outputs[i] = true;
  142. }
  143. }
  144. }
  145. void Logger::addOutputMaxLevel(ILogOutput *out, LogLevel lev)
  146. {
  147. MutexAutoLock lock(m_mutex);
  148. assert(lev < LL_MAX);
  149. for (size_t i = 0; i <= lev; i++) {
  150. m_outputs[i].push_back(out);
  151. m_has_outputs[i] = true;
  152. }
  153. }
  154. LogLevelMask Logger::removeOutput(ILogOutput *out)
  155. {
  156. MutexAutoLock lock(m_mutex);
  157. LogLevelMask ret_mask = 0;
  158. for (size_t i = 0; i < LL_MAX; i++) {
  159. std::vector<ILogOutput *>::iterator it;
  160. it = std::find(m_outputs[i].begin(), m_outputs[i].end(), out);
  161. if (it != m_outputs[i].end()) {
  162. ret_mask |= LOGLEVEL_TO_MASKLEVEL(i);
  163. m_outputs[i].erase(it);
  164. m_has_outputs[i] = !m_outputs[i].empty();
  165. }
  166. }
  167. return ret_mask;
  168. }
  169. void Logger::setLevelSilenced(LogLevel lev, bool silenced)
  170. {
  171. m_silenced_levels[lev] = silenced;
  172. }
  173. void Logger::registerThread(const std::string &name)
  174. {
  175. std::thread::id id = std::this_thread::get_id();
  176. MutexAutoLock lock(m_mutex);
  177. m_thread_names[id] = name;
  178. }
  179. void Logger::deregisterThread()
  180. {
  181. std::thread::id id = std::this_thread::get_id();
  182. MutexAutoLock lock(m_mutex);
  183. m_thread_names.erase(id);
  184. }
  185. const std::string Logger::getLevelLabel(LogLevel lev)
  186. {
  187. static const std::string names[] = {
  188. "",
  189. "ERROR",
  190. "WARNING",
  191. "ACTION",
  192. "INFO",
  193. "VERBOSE",
  194. "TRACE",
  195. };
  196. assert(lev < LL_MAX && lev >= 0);
  197. STATIC_ASSERT(ARRLEN(names) == LL_MAX,
  198. mismatch_between_loglevel_names_and_enum);
  199. return names[lev];
  200. }
  201. LogColor Logger::color_mode = LOG_COLOR_AUTO;
  202. const std::string Logger::getThreadName()
  203. {
  204. std::map<std::thread::id, std::string>::const_iterator it;
  205. std::thread::id id = std::this_thread::get_id();
  206. it = m_thread_names.find(id);
  207. if (it != m_thread_names.end())
  208. return it->second;
  209. std::ostringstream os;
  210. os << "#0x" << std::hex << id;
  211. return os.str();
  212. }
  213. void Logger::log(LogLevel lev, const std::string &text)
  214. {
  215. if (m_silenced_levels[lev])
  216. return;
  217. const std::string thread_name = getThreadName();
  218. const std::string label = getLevelLabel(lev);
  219. const std::string timestamp = getTimestamp();
  220. std::ostringstream os(std::ios_base::binary);
  221. os << timestamp << ": " << label << "[" << thread_name << "]: " << text;
  222. logToOutputs(lev, os.str(), timestamp, thread_name, text);
  223. }
  224. void Logger::logRaw(LogLevel lev, const std::string &text)
  225. {
  226. if (m_silenced_levels[lev])
  227. return;
  228. logToOutputsRaw(lev, text);
  229. }
  230. void Logger::logToOutputsRaw(LogLevel lev, const std::string &line)
  231. {
  232. MutexAutoLock lock(m_mutex);
  233. for (size_t i = 0; i != m_outputs[lev].size(); i++)
  234. m_outputs[lev][i]->logRaw(lev, line);
  235. }
  236. void Logger::logToOutputs(LogLevel lev, const std::string &combined,
  237. const std::string &time, const std::string &thread_name,
  238. const std::string &payload_text)
  239. {
  240. MutexAutoLock lock(m_mutex);
  241. for (size_t i = 0; i != m_outputs[lev].size(); i++)
  242. m_outputs[lev][i]->log(lev, combined, time, thread_name, payload_text);
  243. }
  244. ////
  245. //// *LogOutput methods
  246. ////
  247. void FileLogOutput::setFile(const std::string &filename, s64 file_size_max)
  248. {
  249. // Only move debug.txt if there is a valid maximum file size
  250. bool is_too_large = false;
  251. if (file_size_max > 0) {
  252. std::ifstream ifile(filename, std::ios::binary | std::ios::ate);
  253. is_too_large = ifile.tellg() > file_size_max;
  254. ifile.close();
  255. }
  256. if (is_too_large) {
  257. std::string filename_secondary = filename + ".1";
  258. actionstream << "The log file grew too big; it is moved to " <<
  259. filename_secondary << std::endl;
  260. remove(filename_secondary.c_str());
  261. rename(filename.c_str(), filename_secondary.c_str());
  262. }
  263. m_stream.open(filename, std::ios::app | std::ios::ate);
  264. if (!m_stream.good())
  265. throw FileNotGoodException("Failed to open log file " +
  266. filename + ": " + strerror(errno));
  267. m_stream << "\n\n"
  268. "-------------" << std::endl <<
  269. " Separator" << std::endl <<
  270. "-------------\n" << std::endl;
  271. }
  272. void StreamLogOutput::logRaw(LogLevel lev, const std::string &line)
  273. {
  274. bool colored_message = (Logger::color_mode == LOG_COLOR_ALWAYS) ||
  275. (Logger::color_mode == LOG_COLOR_AUTO && is_tty);
  276. if (colored_message) {
  277. switch (lev) {
  278. case LL_ERROR:
  279. // error is red
  280. m_stream << "\033[91m";
  281. break;
  282. case LL_WARNING:
  283. // warning is yellow
  284. m_stream << "\033[93m";
  285. break;
  286. case LL_INFO:
  287. // info is a bit dark
  288. m_stream << "\033[37m";
  289. break;
  290. case LL_VERBOSE:
  291. case LL_TRACE:
  292. // verbose is darker than info
  293. m_stream << "\033[2m";
  294. break;
  295. default:
  296. // action is white
  297. colored_message = false;
  298. }
  299. }
  300. m_stream << line << std::endl;
  301. if (colored_message) {
  302. // reset to white color
  303. m_stream << "\033[0m";
  304. }
  305. }
  306. void LogOutputBuffer::updateLogLevel()
  307. {
  308. const std::string &conf_loglev = g_settings->get("chat_log_level");
  309. LogLevel log_level = Logger::stringToLevel(conf_loglev);
  310. if (log_level == LL_MAX) {
  311. warningstream << "Supplied unrecognized chat_log_level; "
  312. "showing none." << std::endl;
  313. log_level = LL_NONE;
  314. }
  315. m_logger.removeOutput(this);
  316. m_logger.addOutputMaxLevel(this, log_level);
  317. }
  318. void LogOutputBuffer::logRaw(LogLevel lev, const std::string &line)
  319. {
  320. std::string color;
  321. if (!g_settings->getBool("disable_escape_sequences")) {
  322. switch (lev) {
  323. case LL_ERROR: // red
  324. color = "\x1b(c@#F00)";
  325. break;
  326. case LL_WARNING: // yellow
  327. color = "\x1b(c@#EE0)";
  328. break;
  329. case LL_INFO: // grey
  330. color = "\x1b(c@#BBB)";
  331. break;
  332. case LL_VERBOSE: // dark grey
  333. case LL_TRACE:
  334. color = "\x1b(c@#888)";
  335. break;
  336. default: break;
  337. }
  338. }
  339. MutexAutoLock lock(m_buffer_mutex);
  340. m_buffer.emplace(color.append(line));
  341. }