log.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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 "config.h"
  22. #include "exceptions.h"
  23. #include "util/numeric.h"
  24. #include "log.h"
  25. #include <sstream>
  26. #include <iostream>
  27. #include <algorithm>
  28. #include <cerrno>
  29. #include <cstring>
  30. const int BUFFER_LENGTH = 256;
  31. class StringBuffer : public std::streambuf {
  32. public:
  33. StringBuffer() {
  34. buffer_index = 0;
  35. }
  36. int overflow(int c);
  37. virtual void flush(const std::string &buf) = 0;
  38. std::streamsize xsputn(const char *s, std::streamsize n);
  39. void push_back(char c);
  40. private:
  41. char buffer[BUFFER_LENGTH];
  42. int buffer_index;
  43. };
  44. class LogBuffer : public StringBuffer {
  45. public:
  46. LogBuffer(Logger &logger, LogLevel lev) :
  47. logger(logger),
  48. level(lev)
  49. {}
  50. void flush(const std::string &buffer);
  51. private:
  52. Logger &logger;
  53. LogLevel level;
  54. };
  55. class RawLogBuffer : public StringBuffer {
  56. public:
  57. void flush(const std::string &buffer);
  58. };
  59. ////
  60. //// Globals
  61. ////
  62. Logger g_logger;
  63. StreamLogOutput stdout_output(std::cout);
  64. StreamLogOutput stderr_output(std::cerr);
  65. std::ostream null_stream(NULL);
  66. RawLogBuffer raw_buf;
  67. LogBuffer none_buf(g_logger, LL_NONE);
  68. LogBuffer error_buf(g_logger, LL_ERROR);
  69. LogBuffer warning_buf(g_logger, LL_WARNING);
  70. LogBuffer action_buf(g_logger, LL_ACTION);
  71. LogBuffer info_buf(g_logger, LL_INFO);
  72. LogBuffer verbose_buf(g_logger, LL_VERBOSE);
  73. // Connection
  74. std::ostream *dout_con_ptr = &null_stream;
  75. std::ostream *derr_con_ptr = &verbosestream;
  76. // Server
  77. std::ostream *dout_server_ptr = &infostream;
  78. std::ostream *derr_server_ptr = &errorstream;
  79. #ifndef SERVER
  80. // Client
  81. std::ostream *dout_client_ptr = &infostream;
  82. std::ostream *derr_client_ptr = &errorstream;
  83. #endif
  84. std::ostream rawstream(&raw_buf);
  85. std::ostream dstream(&none_buf);
  86. std::ostream errorstream(&error_buf);
  87. std::ostream warningstream(&warning_buf);
  88. std::ostream actionstream(&action_buf);
  89. std::ostream infostream(&info_buf);
  90. std::ostream verbosestream(&verbose_buf);
  91. // Android
  92. #ifdef __ANDROID__
  93. static unsigned int g_level_to_android[] = {
  94. ANDROID_LOG_INFO, // LL_NONE
  95. //ANDROID_LOG_FATAL,
  96. ANDROID_LOG_ERROR, // LL_ERROR
  97. ANDROID_LOG_WARN, // LL_WARNING
  98. ANDROID_LOG_WARN, // LL_ACTION
  99. //ANDROID_LOG_INFO,
  100. ANDROID_LOG_DEBUG, // LL_INFO
  101. ANDROID_LOG_VERBOSE, // LL_VERBOSE
  102. };
  103. class AndroidSystemLogOutput : public ICombinedLogOutput {
  104. public:
  105. AndroidSystemLogOutput()
  106. {
  107. g_logger.addOutput(this);
  108. }
  109. ~AndroidSystemLogOutput()
  110. {
  111. g_logger.removeOutput(this);
  112. }
  113. void logRaw(LogLevel lev, const std::string &line)
  114. {
  115. STATIC_ASSERT(ARRLEN(g_level_to_android) == LL_MAX,
  116. mismatch_between_android_and_internal_loglevels);
  117. __android_log_print(g_level_to_android[lev],
  118. PROJECT_NAME_C, "%s", line.c_str());
  119. }
  120. };
  121. AndroidSystemLogOutput g_android_log_output;
  122. #endif
  123. ///////////////////////////////////////////////////////////////////////////////
  124. ////
  125. //// Logger
  126. ////
  127. LogLevel Logger::stringToLevel(const std::string &name)
  128. {
  129. if (name == "none")
  130. return LL_NONE;
  131. else if (name == "error")
  132. return LL_ERROR;
  133. else if (name == "warning")
  134. return LL_WARNING;
  135. else if (name == "action")
  136. return LL_ACTION;
  137. else if (name == "info")
  138. return LL_INFO;
  139. else if (name == "verbose")
  140. return LL_VERBOSE;
  141. else
  142. return LL_MAX;
  143. }
  144. void Logger::addOutput(ILogOutput *out)
  145. {
  146. addOutputMaxLevel(out, (LogLevel)(LL_MAX - 1));
  147. }
  148. void Logger::addOutput(ILogOutput *out, LogLevel lev)
  149. {
  150. m_outputs[lev].push_back(out);
  151. }
  152. void Logger::addOutputMasked(ILogOutput *out, LogLevelMask mask)
  153. {
  154. for (size_t i = 0; i < LL_MAX; i++) {
  155. if (mask & LOGLEVEL_TO_MASKLEVEL(i))
  156. m_outputs[i].push_back(out);
  157. }
  158. }
  159. void Logger::addOutputMaxLevel(ILogOutput *out, LogLevel lev)
  160. {
  161. assert(lev < LL_MAX);
  162. for (size_t i = 0; i <= lev; i++)
  163. m_outputs[i].push_back(out);
  164. }
  165. LogLevelMask Logger::removeOutput(ILogOutput *out)
  166. {
  167. LogLevelMask ret_mask = 0;
  168. for (size_t i = 0; i < LL_MAX; i++) {
  169. std::vector<ILogOutput *>::iterator it;
  170. it = std::find(m_outputs[i].begin(), m_outputs[i].end(), out);
  171. if (it != m_outputs[i].end()) {
  172. ret_mask |= LOGLEVEL_TO_MASKLEVEL(i);
  173. m_outputs[i].erase(it);
  174. }
  175. }
  176. return ret_mask;
  177. }
  178. void Logger::setLevelSilenced(LogLevel lev, bool silenced)
  179. {
  180. m_silenced_levels[lev] = silenced;
  181. }
  182. void Logger::registerThread(const std::string &name)
  183. {
  184. std::thread::id id = std::this_thread::get_id();
  185. MutexAutoLock lock(m_mutex);
  186. m_thread_names[id] = name;
  187. }
  188. void Logger::deregisterThread()
  189. {
  190. std::thread::id id = std::this_thread::get_id();
  191. MutexAutoLock lock(m_mutex);
  192. m_thread_names.erase(id);
  193. }
  194. const std::string Logger::getLevelLabel(LogLevel lev)
  195. {
  196. static const std::string names[] = {
  197. "",
  198. "ERROR",
  199. "WARNING",
  200. "ACTION",
  201. "INFO",
  202. "VERBOSE",
  203. };
  204. assert(lev < LL_MAX && lev >= 0);
  205. STATIC_ASSERT(ARRLEN(names) == LL_MAX,
  206. mismatch_between_loglevel_names_and_enum);
  207. return names[lev];
  208. }
  209. const std::string Logger::getThreadName()
  210. {
  211. std::map<std::thread::id, std::string>::const_iterator it;
  212. std::thread::id id = std::this_thread::get_id();
  213. it = m_thread_names.find(id);
  214. if (it != m_thread_names.end())
  215. return it->second;
  216. std::ostringstream os;
  217. os << "#0x" << std::hex << id;
  218. return os.str();
  219. }
  220. void Logger::log(LogLevel lev, const std::string &text)
  221. {
  222. if (m_silenced_levels[lev])
  223. return;
  224. const std::string thread_name = getThreadName();
  225. const std::string label = getLevelLabel(lev);
  226. const std::string timestamp = getTimestamp();
  227. std::ostringstream os(std::ios_base::binary);
  228. os << timestamp << ": " << label << "[" << thread_name << "]: " << text;
  229. logToOutputs(lev, os.str(), timestamp, thread_name, text);
  230. }
  231. void Logger::logRaw(LogLevel lev, const std::string &text)
  232. {
  233. if (m_silenced_levels[lev])
  234. return;
  235. logToOutputsRaw(lev, text);
  236. }
  237. void Logger::logToOutputsRaw(LogLevel lev, const std::string &line)
  238. {
  239. MutexAutoLock lock(m_mutex);
  240. for (size_t i = 0; i != m_outputs[lev].size(); i++)
  241. m_outputs[lev][i]->logRaw(lev, line);
  242. }
  243. void Logger::logToOutputs(LogLevel lev, const std::string &combined,
  244. const std::string &time, const std::string &thread_name,
  245. const std::string &payload_text)
  246. {
  247. MutexAutoLock lock(m_mutex);
  248. for (size_t i = 0; i != m_outputs[lev].size(); i++)
  249. m_outputs[lev][i]->log(lev, combined, time, thread_name, payload_text);
  250. }
  251. ////
  252. //// *LogOutput methods
  253. ////
  254. void FileLogOutput::open(const std::string &filename)
  255. {
  256. m_stream.open(filename.c_str(), std::ios::app | std::ios::ate);
  257. if (!m_stream.good())
  258. throw FileNotGoodException("Failed to open log file " +
  259. filename + ": " + strerror(errno));
  260. m_stream << "\n\n"
  261. "-------------" << std::endl
  262. << " Separator" << std::endl
  263. << "-------------\n" << std::endl;
  264. }
  265. ////
  266. //// *Buffer methods
  267. ////
  268. int StringBuffer::overflow(int c)
  269. {
  270. push_back(c);
  271. return c;
  272. }
  273. std::streamsize StringBuffer::xsputn(const char *s, std::streamsize n)
  274. {
  275. for (int i = 0; i < n; ++i)
  276. push_back(s[i]);
  277. return n;
  278. }
  279. void StringBuffer::push_back(char c)
  280. {
  281. if (c == '\n' || c == '\r') {
  282. if (buffer_index)
  283. flush(std::string(buffer, buffer_index));
  284. buffer_index = 0;
  285. } else {
  286. int index = buffer_index;
  287. buffer[index++] = c;
  288. if (index >= BUFFER_LENGTH) {
  289. flush(std::string(buffer, buffer_index));
  290. buffer_index = 0;
  291. } else {
  292. buffer_index = index;
  293. }
  294. }
  295. }
  296. void LogBuffer::flush(const std::string &buffer)
  297. {
  298. logger.log(level, buffer);
  299. }
  300. void RawLogBuffer::flush(const std::string &buffer)
  301. {
  302. g_logger.logRaw(LL_NONE, buffer);
  303. }