CLogger.h 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. class CLogger;
  13. struct LogRecord;
  14. class ILogTarget;
  15. namespace ELogLevel
  16. {
  17. enum ELogLevel
  18. {
  19. NOT_SET = 0,
  20. TRACE,
  21. DEBUG,
  22. INFO,
  23. WARN,
  24. ERROR
  25. };
  26. }
  27. /// The class CLoggerDomain provides convenient access to super domains from a sub domain.
  28. class DLL_LINKAGE CLoggerDomain
  29. {
  30. public:
  31. /// Constructs a CLoggerDomain with the domain designated by name.
  32. /// Sub-domains can be specified by separating domains by a dot, e.g. "ai.battle". The global domain is named "global".
  33. explicit CLoggerDomain(const std::string & name);
  34. std::string getName() const;
  35. CLoggerDomain getParent() const;
  36. bool isGlobalDomain() const;
  37. static const std::string DOMAIN_GLOBAL;
  38. private:
  39. std::string name;
  40. };
  41. /// The class CLoggerStream provides a stream-like way of logging messages.
  42. class DLL_LINKAGE CLoggerStream
  43. {
  44. public:
  45. CLoggerStream(const CLogger & logger, ELogLevel::ELogLevel level);
  46. ~CLoggerStream();
  47. template<typename T>
  48. CLoggerStream & operator<<(const T & data)
  49. {
  50. if(!sbuffer) sbuffer = new std::stringstream();
  51. (*sbuffer) << data;
  52. return *this;
  53. }
  54. private:
  55. const CLogger & logger;
  56. ELogLevel::ELogLevel level;
  57. std::stringstream * sbuffer;
  58. };
  59. /// The class CLogger is used to log messages to certain targets of a specific domain/name.
  60. class DLL_LINKAGE CLogger
  61. {
  62. public:
  63. inline ELogLevel::ELogLevel getLevel() const;
  64. void setLevel(ELogLevel::ELogLevel level);
  65. const CLoggerDomain & getDomain() const;
  66. /// Logger access methods
  67. static CLogger * getLogger(const CLoggerDomain & domain);
  68. static CLogger * getGlobalLogger();
  69. /// Log methods for various log levels
  70. void trace(const std::string & message) const;
  71. CLoggerStream traceStream() const;
  72. void debug(const std::string & message) const;
  73. CLoggerStream debugStream() const;
  74. void info(const std::string & message) const;
  75. CLoggerStream infoStream() const;
  76. void warn(const std::string & message) const;
  77. CLoggerStream warnStream() const;
  78. void error(const std::string & message) const;
  79. CLoggerStream errorStream() const;
  80. inline void log(ELogLevel::ELogLevel level, const std::string & message) const;
  81. void addTarget(unique_ptr<ILogTarget> && target);
  82. void clearTargets();
  83. /// Returns true if a debug/trace log message will be logged, false if not.
  84. /// Useful if performance is important and concatenating the log message is a expensive task.
  85. bool isDebugEnabled() const;
  86. bool isTraceEnabled() const;
  87. private:
  88. explicit CLogger(const CLoggerDomain & domain);
  89. CLogger * getParent() const;
  90. inline ELogLevel::ELogLevel getEffectiveLevel() const; /// Returns the log level applied on this logger whether directly or indirectly.
  91. inline void callTargets(const LogRecord & record) const;
  92. CLoggerDomain domain;
  93. CLogger * parent;
  94. ELogLevel::ELogLevel level;
  95. std::list<unique_ptr<ILogTarget> > targets;
  96. mutable boost::mutex mx;
  97. static boost::recursive_mutex smx;
  98. };
  99. extern DLL_LINKAGE CLogger * logGlobal;
  100. extern DLL_LINKAGE CLogger * logBonus;
  101. extern DLL_LINKAGE CLogger * logNetwork;
  102. extern DLL_LINKAGE CLogger * logAi;
  103. /// RAII class for tracing the program execution.
  104. /// It prints "Leaving function XYZ" automatically when the object gets destructed.
  105. class DLL_LINKAGE CTraceLogger : boost::noncopyable
  106. {
  107. public:
  108. CTraceLogger(const CLogger * logger, const std::string & beginMessage, const std::string & endMessage);
  109. ~CTraceLogger();
  110. private:
  111. const CLogger * logger;
  112. std::string endMessage;
  113. };
  114. /// Macros for tracing the control flow of the application conveniently. If the LOG_TRACE macro is used it should be
  115. /// the first statement in the function. Logging traces via this macro have almost no impact when the trace is disabled.
  116. ///
  117. #define RAII_TRACE(logger, onEntry, onLeave) \
  118. unique_ptr<CTraceLogger> ctl00; \
  119. if(logger->isTraceEnabled()) \
  120. ctl00 = make_unique<CTraceLogger>(logger, onEntry, onLeave);
  121. #define LOG_TRACE(logger) RAII_TRACE(logger, \
  122. boost::str(boost::format("Entering %s.") % BOOST_CURRENT_FUNCTION), \
  123. boost::str(boost::format("Leaving %s.") % BOOST_CURRENT_FUNCTION))
  124. #define LOG_TRACE_PARAMS(logger, formatStr, params) RAII_TRACE(logger, \
  125. boost::str(boost::format("Entering %s: " + std::string(formatStr) + ".") % BOOST_CURRENT_FUNCTION % params), \
  126. boost::str(boost::format("Leaving %s.") % BOOST_CURRENT_FUNCTION))
  127. /* ---------------------------------------------------------------------------- */
  128. /* Implementation/Detail classes, Private API */
  129. /* ---------------------------------------------------------------------------- */
  130. /// The class CLogManager is a global storage for logger objects.
  131. class DLL_LINKAGE CLogManager : public boost::noncopyable
  132. {
  133. public:
  134. static CLogManager & get();
  135. void addLogger(CLogger * logger);
  136. CLogger * getLogger(const CLoggerDomain & domain); /// Returns a logger or nullptr if no one is registered for the given domain.
  137. private:
  138. CLogManager();
  139. ~CLogManager();
  140. std::map<std::string, CLogger *> loggers;
  141. mutable boost::mutex mx;
  142. static boost::recursive_mutex smx;
  143. };
  144. /// The struct LogRecord holds the log message and additional logging information.
  145. struct DLL_LINKAGE LogRecord
  146. {
  147. LogRecord(const CLoggerDomain & domain, ELogLevel::ELogLevel level, const std::string & message)
  148. : domain(domain), level(level), message(message), timeStamp(boost::posix_time::second_clock::local_time()),
  149. threadId(boost::this_thread::get_id())
  150. {
  151. }
  152. CLoggerDomain domain;
  153. ELogLevel::ELogLevel level;
  154. std::string message;
  155. boost::posix_time::ptime timeStamp;
  156. boost::thread::id threadId;
  157. };
  158. /// The class CLogFormatter formats log records.
  159. ///
  160. /// There are several pattern characters which can be used to format a log record:
  161. /// %d = Date/Time
  162. /// %l = Log level
  163. /// %n = Logger name
  164. /// %t = Thread ID
  165. /// %m = Message
  166. class DLL_LINKAGE CLogFormatter
  167. {
  168. public:
  169. CLogFormatter();
  170. CLogFormatter(const std::string & pattern);
  171. void setPattern(const std::string & pattern);
  172. const std::string & getPattern() const;
  173. std::string format(const LogRecord & record) const;
  174. private:
  175. std::string pattern;
  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. /// The class CLogConsoleTarget is a logging target which writes message to the console.
  196. class DLL_LINKAGE CLogConsoleTarget : public ILogTarget
  197. {
  198. public:
  199. explicit CLogConsoleTarget(CConsoleHandler * console);
  200. bool isColoredOutputEnabled() const;
  201. void setColoredOutputEnabled(bool coloredOutputEnabled);
  202. ELogLevel::ELogLevel getThreshold() const;
  203. void setThreshold(ELogLevel::ELogLevel threshold);
  204. const CLogFormatter & getFormatter() const;
  205. void setFormatter(const CLogFormatter & formatter);
  206. const CColorMapping & getColorMapping() const;
  207. void setColorMapping(const CColorMapping & colorMapping);
  208. void write(const LogRecord & record) override;
  209. private:
  210. CConsoleHandler * console;
  211. ELogLevel::ELogLevel threshold;
  212. bool coloredOutputEnabled;
  213. CLogFormatter formatter;
  214. CColorMapping colorMapping;
  215. mutable boost::mutex mx;
  216. };
  217. /// The class CLogFileTarget is a logging target which writes messages to a log file.
  218. class DLL_LINKAGE CLogFileTarget : public ILogTarget
  219. {
  220. public:
  221. /// Constructs a CLogFileTarget and opens the file designated by filePath. If the append parameter is true, the file
  222. /// will be appended to. Otherwise the file designated by filePath will be truncated before being opened.
  223. explicit CLogFileTarget(const std::string & filePath, bool append = true);
  224. ~CLogFileTarget();
  225. const CLogFormatter & getFormatter() const;
  226. void setFormatter(const CLogFormatter & formatter);
  227. void write(const LogRecord & record) override;
  228. private:
  229. std::ofstream file;
  230. CLogFormatter formatter;
  231. mutable boost::mutex mx;
  232. };