log.cpp 9.6 KB

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