CLogger.h 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. 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 log(ELogLevel::ELogLevel level, const boost::format & fmt) const override;
  74. void addTarget(std::unique_ptr<ILogTarget> && target);
  75. void clearTargets();
  76. /// Returns true if a debug/trace log message will be logged, false if not.
  77. /// Useful if performance is important and concatenating the log message is a expensive task.
  78. bool isDebugEnabled() const;
  79. bool isTraceEnabled() const;
  80. private:
  81. explicit CLogger(const CLoggerDomain & domain);
  82. inline ELogLevel::ELogLevel getEffectiveLevel() const; /// Returns the log level applied on this logger whether directly or indirectly.
  83. inline void callTargets(const LogRecord & record) const;
  84. CLoggerDomain domain;
  85. CLogger * parent;
  86. ELogLevel::ELogLevel level;
  87. std::vector<std::unique_ptr<ILogTarget> > targets;
  88. mutable boost::mutex mx;
  89. static boost::recursive_mutex smx;
  90. };
  91. extern DLL_LINKAGE CLogger * logGlobal;
  92. extern DLL_LINKAGE CLogger * logBonus;
  93. extern DLL_LINKAGE CLogger * logNetwork;
  94. extern DLL_LINKAGE CLogger * logAi;
  95. extern DLL_LINKAGE CLogger * logAnim;
  96. /// RAII class for tracing the program execution.
  97. /// It prints "Leaving function XYZ" automatically when the object gets destructed.
  98. class DLL_LINKAGE CTraceLogger : boost::noncopyable
  99. {
  100. public:
  101. CTraceLogger(const CLogger * logger, const std::string & beginMessage, const std::string & endMessage);
  102. ~CTraceLogger();
  103. private:
  104. const CLogger * logger;
  105. std::string endMessage;
  106. };
  107. /// Macros for tracing the control flow of the application conveniently. If the LOG_TRACE macro is used it should be
  108. /// the first statement in the function. Logging traces via this macro have almost no impact when the trace is disabled.
  109. ///
  110. #define RAII_TRACE(logger, onEntry, onLeave) \
  111. std::unique_ptr<CTraceLogger> ctl00; \
  112. if(logger->isTraceEnabled()) \
  113. ctl00 = make_unique<CTraceLogger>(logger, onEntry, onLeave);
  114. #define LOG_TRACE(logger) RAII_TRACE(logger, \
  115. boost::str(boost::format("Entering %s.") % BOOST_CURRENT_FUNCTION), \
  116. boost::str(boost::format("Leaving %s.") % BOOST_CURRENT_FUNCTION))
  117. #define LOG_TRACE_PARAMS(logger, formatStr, params) RAII_TRACE(logger, \
  118. boost::str(boost::format("Entering %s: " + std::string(formatStr) + ".") % BOOST_CURRENT_FUNCTION % params), \
  119. boost::str(boost::format("Leaving %s.") % BOOST_CURRENT_FUNCTION))
  120. /* ---------------------------------------------------------------------------- */
  121. /* Implementation/Detail classes, Private API */
  122. /* ---------------------------------------------------------------------------- */
  123. /// The class CLogManager is a global storage for logger objects.
  124. class DLL_LINKAGE CLogManager : public boost::noncopyable
  125. {
  126. public:
  127. static CLogManager & get();
  128. void addLogger(CLogger * logger);
  129. CLogger * getLogger(const CLoggerDomain & domain); /// Returns a logger or nullptr if no one is registered for the given domain.
  130. std::vector<std::string> getRegisteredDomains() const;
  131. private:
  132. CLogManager();
  133. virtual ~CLogManager();
  134. std::map<std::string, CLogger *> loggers;
  135. mutable boost::mutex mx;
  136. static boost::recursive_mutex smx;
  137. };
  138. /// The struct LogRecord holds the log message and additional logging information.
  139. struct DLL_LINKAGE LogRecord
  140. {
  141. LogRecord(const CLoggerDomain & domain, ELogLevel::ELogLevel level, const std::string & message)
  142. : domain(domain),
  143. level(level),
  144. message(message),
  145. timeStamp(boost::posix_time::microsec_clock::local_time()),
  146. threadId(boost::lexical_cast<std::string>(boost::this_thread::get_id())) { }
  147. CLoggerDomain domain;
  148. ELogLevel::ELogLevel level;
  149. std::string message;
  150. boost::posix_time::ptime timeStamp;
  151. std::string threadId;
  152. };
  153. /// The class CLogFormatter formats log records.
  154. ///
  155. /// There are several pattern characters which can be used to format a log record:
  156. /// %d = Date/Time
  157. /// %l = Log level
  158. /// %n = Logger name
  159. /// %t = Thread ID
  160. /// %m = Message
  161. class DLL_LINKAGE CLogFormatter
  162. {
  163. public:
  164. CLogFormatter();
  165. CLogFormatter(const CLogFormatter & copy);
  166. CLogFormatter(CLogFormatter && move);
  167. CLogFormatter(const std::string & pattern);
  168. CLogFormatter & operator=(const CLogFormatter & copy);
  169. CLogFormatter & operator=(CLogFormatter && move);
  170. void setPattern(const std::string & pattern);
  171. void setPattern(std::string && pattern);
  172. const std::string & getPattern() const;
  173. std::string format(const LogRecord & record) const;
  174. private:
  175. std::string pattern;
  176. mutable std::stringstream dateStream;
  177. };
  178. /// The interface ILogTarget is used by all log target implementations. It holds
  179. /// the abstract method write which sub-classes should implement.
  180. class DLL_LINKAGE ILogTarget : public boost::noncopyable
  181. {
  182. public:
  183. virtual ~ILogTarget() { };
  184. virtual void write(const LogRecord & record) = 0;
  185. };
  186. /// The class CColorMapping maps a logger name and a level to a specific color. Supports domain inheritance.
  187. class DLL_LINKAGE CColorMapping
  188. {
  189. public:
  190. CColorMapping();
  191. void setColorFor(const CLoggerDomain & domain, ELogLevel::ELogLevel level, EConsoleTextColor::EConsoleTextColor color);
  192. EConsoleTextColor::EConsoleTextColor getColorFor(const CLoggerDomain & domain, ELogLevel::ELogLevel level) const;
  193. private:
  194. std::map<std::string, std::map<ELogLevel::ELogLevel, EConsoleTextColor::EConsoleTextColor> > map;
  195. };
  196. /// This target is a logging target which writes message to the console.
  197. /// The target may be shared among multiple loggers. All methods except write aren't thread-safe.
  198. /// The console target is intended to be configured once and then added to a logger.
  199. class DLL_LINKAGE CLogConsoleTarget : public ILogTarget
  200. {
  201. public:
  202. explicit CLogConsoleTarget(CConsoleHandler * console);
  203. bool isColoredOutputEnabled() const;
  204. void setColoredOutputEnabled(bool coloredOutputEnabled);
  205. ELogLevel::ELogLevel getThreshold() const;
  206. void setThreshold(ELogLevel::ELogLevel threshold);
  207. const CLogFormatter & getFormatter() const;
  208. void setFormatter(const CLogFormatter & formatter);
  209. const CColorMapping & getColorMapping() const;
  210. void setColorMapping(const CColorMapping & colorMapping);
  211. void write(const LogRecord & record) override;
  212. private:
  213. CConsoleHandler * console;
  214. ELogLevel::ELogLevel threshold;
  215. bool coloredOutputEnabled;
  216. CLogFormatter formatter;
  217. CColorMapping colorMapping;
  218. mutable boost::mutex mx;
  219. };
  220. /// This target is a logging target which writes messages to a log file.
  221. /// The target may be shared among multiple loggers. All methods except write aren't thread-safe.
  222. /// The file target is intended to be configured once and then added to a logger.
  223. class DLL_LINKAGE CLogFileTarget : public ILogTarget
  224. {
  225. public:
  226. /// Constructs a CLogFileTarget and opens the file designated by filePath. If the append parameter is true, the file
  227. /// will be appended to. Otherwise the file designated by filePath will be truncated before being opened.
  228. explicit CLogFileTarget(boost::filesystem::path filePath, bool append = true);
  229. const CLogFormatter & getFormatter() const;
  230. void setFormatter(const CLogFormatter & formatter);
  231. void write(const LogRecord & record) override;
  232. private:
  233. FileStream file;
  234. CLogFormatter formatter;
  235. mutable boost::mutex mx;
  236. };