CLogger.h 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 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. std::vector<std::string> getRegisteredDomains() const;
  130. private:
  131. CLogManager();
  132. virtual ~CLogManager();
  133. std::map<std::string, CLogger *> loggers;
  134. mutable boost::mutex mx;
  135. static boost::recursive_mutex smx;
  136. };
  137. /// The struct LogRecord holds the log message and additional logging information.
  138. struct DLL_LINKAGE LogRecord
  139. {
  140. LogRecord(const CLoggerDomain & domain, ELogLevel::ELogLevel level, const std::string & message)
  141. : domain(domain),
  142. level(level),
  143. message(message),
  144. timeStamp(boost::posix_time::microsec_clock::local_time()),
  145. threadId(boost::lexical_cast<std::string>(boost::this_thread::get_id())) { }
  146. CLoggerDomain domain;
  147. ELogLevel::ELogLevel level;
  148. std::string message;
  149. boost::posix_time::ptime timeStamp;
  150. std::string threadId;
  151. };
  152. /// The class CLogFormatter formats log records.
  153. ///
  154. /// There are several pattern characters which can be used to format a log record:
  155. /// %d = Date/Time
  156. /// %l = Log level
  157. /// %n = Logger name
  158. /// %t = Thread ID
  159. /// %m = Message
  160. class DLL_LINKAGE CLogFormatter
  161. {
  162. public:
  163. CLogFormatter();
  164. CLogFormatter(const CLogFormatter & copy);
  165. CLogFormatter(CLogFormatter && move);
  166. CLogFormatter(const std::string & pattern);
  167. CLogFormatter & operator=(const CLogFormatter & copy);
  168. CLogFormatter & operator=(CLogFormatter && move);
  169. void setPattern(const std::string & pattern);
  170. void setPattern(std::string && pattern);
  171. const std::string & getPattern() const;
  172. std::string format(const LogRecord & record) const;
  173. private:
  174. std::string pattern;
  175. mutable std::stringstream dateStream;
  176. };
  177. /// The interface ILogTarget is used by all log target implementations. It holds
  178. /// the abstract method write which sub-classes should implement.
  179. class DLL_LINKAGE ILogTarget : public boost::noncopyable
  180. {
  181. public:
  182. virtual ~ILogTarget() { };
  183. virtual void write(const LogRecord & record) = 0;
  184. };
  185. /// The class CColorMapping maps a logger name and a level to a specific color. Supports domain inheritance.
  186. class DLL_LINKAGE CColorMapping
  187. {
  188. public:
  189. CColorMapping();
  190. void setColorFor(const CLoggerDomain & domain, ELogLevel::ELogLevel level, EConsoleTextColor::EConsoleTextColor color);
  191. EConsoleTextColor::EConsoleTextColor getColorFor(const CLoggerDomain & domain, ELogLevel::ELogLevel level) const;
  192. private:
  193. std::map<std::string, std::map<ELogLevel::ELogLevel, EConsoleTextColor::EConsoleTextColor> > map;
  194. };
  195. /// This target is a logging target which writes message to the console.
  196. /// The target may be shared among multiple loggers. All methods except write aren't thread-safe.
  197. /// The console target is intended to be configured once and then added to a logger.
  198. class DLL_LINKAGE CLogConsoleTarget : public ILogTarget
  199. {
  200. public:
  201. explicit CLogConsoleTarget(CConsoleHandler * console);
  202. bool isColoredOutputEnabled() const;
  203. void setColoredOutputEnabled(bool coloredOutputEnabled);
  204. ELogLevel::ELogLevel getThreshold() const;
  205. void setThreshold(ELogLevel::ELogLevel threshold);
  206. const CLogFormatter & getFormatter() const;
  207. void setFormatter(const CLogFormatter & formatter);
  208. const CColorMapping & getColorMapping() const;
  209. void setColorMapping(const CColorMapping & colorMapping);
  210. void write(const LogRecord & record) override;
  211. private:
  212. CConsoleHandler * console;
  213. ELogLevel::ELogLevel threshold;
  214. bool coloredOutputEnabled;
  215. CLogFormatter formatter;
  216. CColorMapping colorMapping;
  217. mutable boost::mutex mx;
  218. };
  219. /// This target is a logging target which writes messages to a log file.
  220. /// The target may be shared among multiple loggers. All methods except write aren't thread-safe.
  221. /// The file target is intended to be configured once and then added to a logger.
  222. class DLL_LINKAGE CLogFileTarget : public ILogTarget
  223. {
  224. public:
  225. /// Constructs a CLogFileTarget and opens the file designated by filePath. If the append parameter is true, the file
  226. /// will be appended to. Otherwise the file designated by filePath will be truncated before being opened.
  227. explicit CLogFileTarget(boost::filesystem::path filePath, bool append = true);
  228. const CLogFormatter & getFormatter() const;
  229. void setFormatter(const CLogFormatter & formatter);
  230. void write(const LogRecord & record) override;
  231. private:
  232. FileStream file;
  233. CLogFormatter formatter;
  234. mutable boost::mutex mx;
  235. };