CLogger.h 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /*
  2. * CLogger.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include "../CConsoleHandler.h"
  12. #include "../filesystem/FileStream.h"
  13. class CLogger;
  14. struct LogRecord;
  15. class ILogTarget;
  16. namespace ELogLevel
  17. {
  18. #ifdef VCMI_ANDROID
  19. int toAndroid(ELogLevel logLevel);
  20. #endif
  21. }
  22. /// The class CLoggerDomain provides convenient access to super domains from a sub domain.
  23. class DLL_LINKAGE CLoggerDomain
  24. {
  25. public:
  26. /// Constructs a CLoggerDomain with the domain designated by name.
  27. /// Sub-domains can be specified by separating domains by a dot, e.g. "ai.battle". The global domain is named "global".
  28. explicit CLoggerDomain(std::string name);
  29. const std::string& getName() const;
  30. CLoggerDomain getParent() const;
  31. bool isGlobalDomain() const;
  32. static const std::string DOMAIN_GLOBAL;
  33. private:
  34. std::string name;
  35. };
  36. /// The class CLoggerStream provides a stream-like way of logging messages.
  37. class DLL_LINKAGE CLoggerStream
  38. {
  39. public:
  40. CLoggerStream(const CLogger & logger, ELogLevel::ELogLevel level);
  41. ~CLoggerStream();
  42. template<typename T>
  43. CLoggerStream & operator<<(const T & data)
  44. {
  45. if(!sbuffer)
  46. sbuffer = new std::stringstream(std::ios_base::out);
  47. (*sbuffer) << data;
  48. return *this;
  49. }
  50. private:
  51. const CLogger & logger;
  52. ELogLevel::ELogLevel level;
  53. std::stringstream * sbuffer;
  54. };
  55. /// The logger is used to log messages to certain targets of a specific domain/name.
  56. /// It is thread-safe and can be used concurrently by several threads.
  57. class DLL_LINKAGE CLogger: public vstd::CLoggerBase
  58. {
  59. public:
  60. inline ELogLevel::ELogLevel getLevel() const;
  61. void setLevel(ELogLevel::ELogLevel level);
  62. const CLoggerDomain & getDomain() const;
  63. /// Logger access methods
  64. static CLogger * getLogger(const CLoggerDomain & domain);
  65. static CLogger * getGlobalLogger();
  66. /// Log streams for various log levels
  67. CLoggerStream traceStream() const;
  68. CLoggerStream debugStream() const;
  69. CLoggerStream infoStream() const;
  70. CLoggerStream warnStream() const;
  71. CLoggerStream errorStream() const;
  72. void log(ELogLevel::ELogLevel level, const std::string & message) const override;
  73. void addTarget(std::unique_ptr<ILogTarget> && target);
  74. void clearTargets();
  75. /// Returns true if a debug/trace log message will be logged, false if not.
  76. /// Useful if performance is important and concatenating the log message is a expensive task.
  77. bool isDebugEnabled() const;
  78. bool isTraceEnabled() const;
  79. private:
  80. explicit CLogger(const CLoggerDomain & domain);
  81. inline ELogLevel::ELogLevel getEffectiveLevel() const; /// Returns the log level applied on this logger whether directly or indirectly.
  82. inline void callTargets(const LogRecord & record) const;
  83. CLoggerDomain domain;
  84. CLogger * parent;
  85. ELogLevel::ELogLevel level;
  86. std::vector<std::unique_ptr<ILogTarget> > targets;
  87. mutable boost::mutex mx;
  88. static boost::recursive_mutex smx;
  89. };
  90. extern DLL_LINKAGE CLogger * logGlobal;
  91. extern DLL_LINKAGE CLogger * logBonus;
  92. extern DLL_LINKAGE CLogger * logNetwork;
  93. extern DLL_LINKAGE CLogger * logAi;
  94. extern DLL_LINKAGE CLogger * logAnim;
  95. /// RAII class for tracing the program execution.
  96. /// It prints "Leaving function XYZ" automatically when the object gets destructed.
  97. class DLL_LINKAGE CTraceLogger : boost::noncopyable
  98. {
  99. public:
  100. CTraceLogger(const CLogger * logger, const std::string & beginMessage, const std::string & endMessage);
  101. ~CTraceLogger();
  102. private:
  103. const CLogger * logger;
  104. std::string endMessage;
  105. };
  106. /// Macros for tracing the control flow of the application conveniently. If the LOG_TRACE macro is used it should be
  107. /// the first statement in the function. Logging traces via this macro have almost no impact when the trace is disabled.
  108. ///
  109. #define RAII_TRACE(logger, onEntry, onLeave) \
  110. std::unique_ptr<CTraceLogger> ctl00; \
  111. if(logger->isTraceEnabled()) \
  112. ctl00 = make_unique<CTraceLogger>(logger, onEntry, onLeave);
  113. #define LOG_TRACE(logger) RAII_TRACE(logger, \
  114. boost::str(boost::format("Entering %s.") % BOOST_CURRENT_FUNCTION), \
  115. boost::str(boost::format("Leaving %s.") % BOOST_CURRENT_FUNCTION))
  116. #define LOG_TRACE_PARAMS(logger, formatStr, params) RAII_TRACE(logger, \
  117. boost::str(boost::format("Entering %s: " + std::string(formatStr) + ".") % BOOST_CURRENT_FUNCTION % params), \
  118. boost::str(boost::format("Leaving %s.") % BOOST_CURRENT_FUNCTION))
  119. /* ---------------------------------------------------------------------------- */
  120. /* Implementation/Detail classes, Private API */
  121. /* ---------------------------------------------------------------------------- */
  122. /// The class CLogManager is a global storage for logger objects.
  123. class DLL_LINKAGE CLogManager : public boost::noncopyable
  124. {
  125. public:
  126. static CLogManager & get();
  127. void addLogger(CLogger * logger);
  128. CLogger * getLogger(const CLoggerDomain & domain); /// Returns a logger or nullptr if no one is registered for the given domain.
  129. private:
  130. CLogManager();
  131. ~CLogManager();
  132. std::map<std::string, CLogger *> loggers;
  133. mutable boost::mutex mx;
  134. static boost::recursive_mutex smx;
  135. };
  136. /// The struct LogRecord holds the log message and additional logging information.
  137. struct DLL_LINKAGE LogRecord
  138. {
  139. LogRecord(const CLoggerDomain & domain, ELogLevel::ELogLevel level, const std::string & message)
  140. : domain(domain),
  141. level(level),
  142. message(message),
  143. timeStamp(boost::posix_time::microsec_clock::local_time()),
  144. threadId(boost::lexical_cast<std::string>(boost::this_thread::get_id())) { }
  145. CLoggerDomain domain;
  146. ELogLevel::ELogLevel level;
  147. std::string message;
  148. boost::posix_time::ptime timeStamp;
  149. std::string threadId;
  150. };
  151. /// The class CLogFormatter formats log records.
  152. ///
  153. /// There are several pattern characters which can be used to format a log record:
  154. /// %d = Date/Time
  155. /// %l = Log level
  156. /// %n = Logger name
  157. /// %t = Thread ID
  158. /// %m = Message
  159. class DLL_LINKAGE CLogFormatter
  160. {
  161. public:
  162. CLogFormatter();
  163. CLogFormatter(const CLogFormatter & copy);
  164. CLogFormatter(CLogFormatter && move);
  165. CLogFormatter(const std::string & pattern);
  166. CLogFormatter & operator=(const CLogFormatter & copy);
  167. CLogFormatter & operator=(CLogFormatter && move);
  168. void setPattern(const std::string & pattern);
  169. void setPattern(std::string && pattern);
  170. const std::string & getPattern() const;
  171. std::string format(const LogRecord & record) const;
  172. private:
  173. std::string pattern;
  174. mutable std::stringstream dateStream;
  175. };
  176. /// The interface ILogTarget is used by all log target implementations. It holds
  177. /// the abstract method write which sub-classes should implement.
  178. class DLL_LINKAGE ILogTarget : public boost::noncopyable
  179. {
  180. public:
  181. virtual ~ILogTarget() { };
  182. virtual void write(const LogRecord & record) = 0;
  183. };
  184. /// The class CColorMapping maps a logger name and a level to a specific color. Supports domain inheritance.
  185. class DLL_LINKAGE CColorMapping
  186. {
  187. public:
  188. CColorMapping();
  189. void setColorFor(const CLoggerDomain & domain, ELogLevel::ELogLevel level, EConsoleTextColor::EConsoleTextColor color);
  190. EConsoleTextColor::EConsoleTextColor getColorFor(const CLoggerDomain & domain, ELogLevel::ELogLevel level) const;
  191. private:
  192. std::map<std::string, std::map<ELogLevel::ELogLevel, EConsoleTextColor::EConsoleTextColor> > map;
  193. };
  194. /// This target is a logging target which writes message to the console.
  195. /// The target may be shared among multiple loggers. All methods except write aren't thread-safe.
  196. /// The console target is intended to be configured once and then added to a logger.
  197. class DLL_LINKAGE CLogConsoleTarget : public ILogTarget
  198. {
  199. public:
  200. explicit CLogConsoleTarget(CConsoleHandler * console);
  201. bool isColoredOutputEnabled() const;
  202. void setColoredOutputEnabled(bool coloredOutputEnabled);
  203. ELogLevel::ELogLevel getThreshold() const;
  204. void setThreshold(ELogLevel::ELogLevel threshold);
  205. const CLogFormatter & getFormatter() const;
  206. void setFormatter(const CLogFormatter & formatter);
  207. const CColorMapping & getColorMapping() const;
  208. void setColorMapping(const CColorMapping & colorMapping);
  209. void write(const LogRecord & record) override;
  210. private:
  211. CConsoleHandler * console;
  212. ELogLevel::ELogLevel threshold;
  213. bool coloredOutputEnabled;
  214. CLogFormatter formatter;
  215. CColorMapping colorMapping;
  216. mutable boost::mutex mx;
  217. };
  218. /// This target is a logging target which writes messages to a log file.
  219. /// The target may be shared among multiple loggers. All methods except write aren't thread-safe.
  220. /// The file target is intended to be configured once and then added to a logger.
  221. class DLL_LINKAGE CLogFileTarget : public ILogTarget
  222. {
  223. public:
  224. /// Constructs a CLogFileTarget and opens the file designated by filePath. If the append parameter is true, the file
  225. /// will be appended to. Otherwise the file designated by filePath will be truncated before being opened.
  226. explicit CLogFileTarget(boost::filesystem::path filePath, bool append = true);
  227. const CLogFormatter & getFormatter() const;
  228. void setFormatter(const CLogFormatter & formatter);
  229. void write(const LogRecord & record) override;
  230. private:
  231. FileStream file;
  232. CLogFormatter formatter;
  233. mutable boost::mutex mx;
  234. };