log.h 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. #pragma once
  17. #include <atomic>
  18. #include <map>
  19. #include <queue>
  20. #include <string>
  21. #include <fstream>
  22. #include <thread>
  23. #include <mutex>
  24. #if !defined(_WIN32) // POSIX
  25. #include <unistd.h>
  26. #endif
  27. #include "threading/mutex_auto_lock.h"
  28. #include "util/basic_macros.h"
  29. #include "util/stream.h"
  30. #include "irrlichttypes.h"
  31. class ILogOutput;
  32. enum LogLevel {
  33. LL_NONE, // Special level that is always printed
  34. LL_ERROR,
  35. LL_WARNING,
  36. LL_ACTION, // In-game actions
  37. LL_INFO,
  38. LL_VERBOSE,
  39. LL_TRACE,
  40. LL_MAX,
  41. };
  42. enum LogColor {
  43. LOG_COLOR_NEVER,
  44. LOG_COLOR_ALWAYS,
  45. LOG_COLOR_AUTO,
  46. };
  47. typedef u8 LogLevelMask;
  48. #define LOGLEVEL_TO_MASKLEVEL(x) (1 << x)
  49. class Logger {
  50. public:
  51. void addOutput(ILogOutput *out);
  52. void addOutput(ILogOutput *out, LogLevel lev);
  53. void addOutputMasked(ILogOutput *out, LogLevelMask mask);
  54. void addOutputMaxLevel(ILogOutput *out, LogLevel lev);
  55. LogLevelMask removeOutput(ILogOutput *out);
  56. void setLevelSilenced(LogLevel lev, bool silenced);
  57. void registerThread(const std::string &name);
  58. void deregisterThread();
  59. void log(LogLevel lev, const std::string &text);
  60. // Logs without a prefix
  61. void logRaw(LogLevel lev, const std::string &text);
  62. static LogLevel stringToLevel(const std::string &name);
  63. static const std::string getLevelLabel(LogLevel lev);
  64. bool hasOutput(LogLevel level) {
  65. return m_has_outputs[level].load(std::memory_order_relaxed);
  66. }
  67. static LogColor color_mode;
  68. private:
  69. void logToOutputsRaw(LogLevel, const std::string &line);
  70. void logToOutputs(LogLevel, const std::string &combined,
  71. const std::string &time, const std::string &thread_name,
  72. const std::string &payload_text);
  73. const std::string getThreadName();
  74. std::vector<ILogOutput *> m_outputs[LL_MAX];
  75. std::atomic<bool> m_has_outputs[LL_MAX];
  76. // Should implement atomic loads and stores (even though it's only
  77. // written to when one thread has access currently).
  78. // Works on all known architectures (x86, ARM, MIPS).
  79. volatile bool m_silenced_levels[LL_MAX];
  80. std::map<std::thread::id, std::string> m_thread_names;
  81. mutable std::mutex m_mutex;
  82. };
  83. class ILogOutput {
  84. public:
  85. virtual void logRaw(LogLevel, const std::string &line) = 0;
  86. virtual void log(LogLevel, const std::string &combined,
  87. const std::string &time, const std::string &thread_name,
  88. const std::string &payload_text) = 0;
  89. };
  90. class ICombinedLogOutput : public ILogOutput {
  91. public:
  92. void log(LogLevel lev, const std::string &combined,
  93. const std::string &time, const std::string &thread_name,
  94. const std::string &payload_text)
  95. {
  96. logRaw(lev, combined);
  97. }
  98. };
  99. class StreamLogOutput : public ICombinedLogOutput {
  100. public:
  101. StreamLogOutput(std::ostream &stream) :
  102. m_stream(stream)
  103. {
  104. #if !defined(_WIN32)
  105. if (&stream == &std::cout)
  106. is_tty = isatty(STDOUT_FILENO);
  107. else if (&stream == &std::cerr)
  108. is_tty = isatty(STDERR_FILENO);
  109. #endif
  110. }
  111. void logRaw(LogLevel lev, const std::string &line);
  112. private:
  113. std::ostream &m_stream;
  114. bool is_tty = false;
  115. };
  116. class FileLogOutput : public ICombinedLogOutput {
  117. public:
  118. void setFile(const std::string &filename, s64 file_size_max);
  119. void logRaw(LogLevel lev, const std::string &line)
  120. {
  121. m_stream << line << std::endl;
  122. }
  123. private:
  124. std::ofstream m_stream;
  125. };
  126. class LogOutputBuffer : public ICombinedLogOutput {
  127. public:
  128. LogOutputBuffer(Logger &logger) :
  129. m_logger(logger)
  130. {
  131. updateLogLevel();
  132. };
  133. virtual ~LogOutputBuffer()
  134. {
  135. m_logger.removeOutput(this);
  136. }
  137. void updateLogLevel();
  138. void logRaw(LogLevel lev, const std::string &line);
  139. void clear()
  140. {
  141. MutexAutoLock lock(m_buffer_mutex);
  142. m_buffer = std::queue<std::string>();
  143. }
  144. bool empty() const
  145. {
  146. MutexAutoLock lock(m_buffer_mutex);
  147. return m_buffer.empty();
  148. }
  149. std::string get()
  150. {
  151. MutexAutoLock lock(m_buffer_mutex);
  152. if (m_buffer.empty())
  153. return "";
  154. std::string s = std::move(m_buffer.front());
  155. m_buffer.pop();
  156. return s;
  157. }
  158. private:
  159. // g_logger serializes calls to logRaw() with a mutex, but that
  160. // doesn't prevent get() / clear() from being called on top of it.
  161. // This mutex prevents that.
  162. mutable std::mutex m_buffer_mutex;
  163. std::queue<std::string> m_buffer;
  164. Logger &m_logger;
  165. };
  166. #ifdef __ANDROID__
  167. class AndroidLogOutput : public ICombinedLogOutput {
  168. public:
  169. void logRaw(LogLevel lev, const std::string &line);
  170. };
  171. #endif
  172. /*
  173. * LogTarget
  174. *
  175. * This is the interface that sits between the LogStreams and the global logger.
  176. * Primarily used to route streams to log levels, but could also enable other
  177. * custom behavior.
  178. *
  179. */
  180. class LogTarget {
  181. public:
  182. // Must be thread-safe. These can be called from any thread.
  183. virtual bool hasOutput() = 0;
  184. virtual void log(const std::string &buf) = 0;
  185. };
  186. /*
  187. * StreamProxy
  188. *
  189. * An ostream-like object that can proxy to a real ostream or do nothing,
  190. * depending on how it is configured. See LogStream below.
  191. *
  192. */
  193. class StreamProxy {
  194. public:
  195. StreamProxy(std::ostream *os) : m_os(os) { }
  196. template<typename T>
  197. StreamProxy& operator<<(T&& arg) {
  198. if (m_os) {
  199. *m_os << std::forward<T>(arg);
  200. }
  201. return *this;
  202. }
  203. StreamProxy& operator<<(std::ostream& (*manip)(std::ostream&)) {
  204. if (m_os) {
  205. *m_os << manip;
  206. }
  207. return *this;
  208. }
  209. private:
  210. std::ostream *m_os;
  211. };
  212. /*
  213. * LogStream
  214. *
  215. * The public interface for log streams (infostream, verbosestream, etc).
  216. *
  217. * LogStream minimizes the work done when a given stream is off. (meaning
  218. * it has no output targets, so it goes to /dev/null)
  219. *
  220. * For example, consider:
  221. *
  222. * verbosestream << "hello world" << 123 << std::endl;
  223. *
  224. * The compiler evaluates this as:
  225. *
  226. * (((verbosestream << "hello world") << 123) << std::endl)
  227. * ^ ^
  228. *
  229. * If `verbosestream` is on, the innermost expression (marked by ^) will return
  230. * a StreamProxy that forwards to a real ostream, that feeds into the logger.
  231. * However, if `verbosestream` is off, it will return a StreamProxy that does
  232. * nothing on all later operations. Specifically, CPU time won't be wasted
  233. * writing "hello world" and 123 into a buffer, or formatting the log entry.
  234. *
  235. * It is also possible to directly check if the stream is on/off:
  236. *
  237. * if (verbosestream) {
  238. * auto data = ComputeExpensiveDataForTheLog();
  239. * verbosestream << data << endl;
  240. * }
  241. *
  242. */
  243. class LogStream {
  244. public:
  245. LogStream() = delete;
  246. DISABLE_CLASS_COPY(LogStream);
  247. LogStream(LogTarget &target) :
  248. m_target(target),
  249. m_buffer(std::bind(&LogStream::internalFlush, this, std::placeholders::_1)),
  250. m_dummy_buffer(),
  251. m_stream(&m_buffer),
  252. m_dummy_stream(&m_dummy_buffer),
  253. m_proxy(&m_stream),
  254. m_dummy_proxy(nullptr) { }
  255. template<typename T>
  256. StreamProxy& operator<<(T&& arg) {
  257. StreamProxy& sp = m_target.hasOutput() ? m_proxy : m_dummy_proxy;
  258. sp << std::forward<T>(arg);
  259. return sp;
  260. }
  261. StreamProxy& operator<<(std::ostream& (*manip)(std::ostream&)) {
  262. StreamProxy& sp = m_target.hasOutput() ? m_proxy : m_dummy_proxy;
  263. sp << manip;
  264. return sp;
  265. }
  266. operator bool() {
  267. return m_target.hasOutput();
  268. }
  269. void internalFlush(const std::string &buf) {
  270. m_target.log(buf);
  271. }
  272. operator std::ostream&() {
  273. return m_target.hasOutput() ? m_stream : m_dummy_stream;
  274. }
  275. private:
  276. // 10 streams per thread x (256 + overhead) ~ 3K per thread
  277. static const int BUFFER_LENGTH = 256;
  278. LogTarget &m_target;
  279. StringStreamBuffer<BUFFER_LENGTH> m_buffer;
  280. DummyStreamBuffer m_dummy_buffer;
  281. std::ostream m_stream;
  282. std::ostream m_dummy_stream;
  283. StreamProxy m_proxy;
  284. StreamProxy m_dummy_proxy;
  285. };
  286. #ifdef __ANDROID__
  287. extern AndroidLogOutput stdout_output;
  288. extern AndroidLogOutput stderr_output;
  289. #else
  290. extern StreamLogOutput stdout_output;
  291. extern StreamLogOutput stderr_output;
  292. #endif
  293. extern Logger g_logger;
  294. /*
  295. * By making the streams thread_local, each thread has its own
  296. * private buffer. Two or more threads can write to the same stream
  297. * simultaneously (lock-free), and there won't be any interference.
  298. *
  299. * The finished lines are sent to a LogTarget which is a global (not thread-local)
  300. * object, and from there relayed to g_logger. The final writes are serialized
  301. * by the mutex in g_logger.
  302. */
  303. extern thread_local LogStream dstream;
  304. extern thread_local LogStream rawstream; // Writes directly to all LL_NONE log outputs with no prefix.
  305. extern thread_local LogStream errorstream;
  306. extern thread_local LogStream warningstream;
  307. extern thread_local LogStream actionstream;
  308. extern thread_local LogStream infostream;
  309. extern thread_local LogStream verbosestream;
  310. extern thread_local LogStream tracestream;
  311. // TODO: Search/replace these with verbose/tracestream
  312. extern thread_local LogStream derr_con;
  313. extern thread_local LogStream dout_con;
  314. #define TRACESTREAM(x) do { \
  315. if (tracestream) { \
  316. tracestream x; \
  317. } \
  318. } while (0)