CLogger.h 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. /// Macros for tracing the control flow of the application conveniently. If the TRACE_BEGIN macro is used it should be
  104. /// the first statement in the function, whereas the TRACE_END should be last one before a return statement.
  105. /// Logging traces via this macro have almost no impact when the trace is disabled.
  106. #define TRACE_BEGIN(logger) logger->traceStream() << boost::format("Entering %s.") % BOOST_CURRENT_FUNCTION;
  107. #define TRACE_BEGIN_PARAMS(logger, formatStr, params) if(logger->isTraceEnabled()) logger->traceStream() << \
  108. boost::format("Entering %s: " + std::string(formatStr) + ".") % BOOST_CURRENT_FUNCTION % params;
  109. #define TRACE_END(logger) logger->traceStream() << boost::format("Leaving %s.") % BOOST_CURRENT_FUNCTION;
  110. #define TRACE_END_PARAMS(logger, formatStr, params) if(logger->isTraceEnabled()) logger->traceStream() << \
  111. boost::format("Leaving %s: " + std::string(formatStr) + ".") % BOOST_CURRENT_FUNCTION % params;
  112. /* ---------------------------------------------------------------------------- */
  113. /* Implementation/Detail classes, Private API */
  114. /* ---------------------------------------------------------------------------- */
  115. /// The class CLogManager is a global storage for logger objects.
  116. class DLL_LINKAGE CLogManager : public boost::noncopyable
  117. {
  118. public:
  119. static CLogManager & get();
  120. void addLogger(CLogger * logger);
  121. CLogger * getLogger(const CLoggerDomain & domain); /// Returns a logger or nullptr if no one is registered for the given domain.
  122. private:
  123. CLogManager();
  124. ~CLogManager();
  125. std::map<std::string, CLogger *> loggers;
  126. mutable boost::mutex mx;
  127. static boost::recursive_mutex smx;
  128. };
  129. /// The struct LogRecord holds the log message and additional logging information.
  130. struct DLL_LINKAGE LogRecord
  131. {
  132. LogRecord(const CLoggerDomain & domain, ELogLevel::ELogLevel level, const std::string & message)
  133. : domain(domain), level(level), message(message), timeStamp(boost::posix_time::second_clock::local_time()),
  134. threadId(boost::this_thread::get_id())
  135. {
  136. }
  137. CLoggerDomain domain;
  138. ELogLevel::ELogLevel level;
  139. std::string message;
  140. boost::posix_time::ptime timeStamp;
  141. boost::thread::id threadId;
  142. };
  143. /// The class CLogFormatter formats log records.
  144. ///
  145. /// There are several pattern characters which can be used to format a log record:
  146. /// %d = Date/Time
  147. /// %l = Log level
  148. /// %n = Logger name
  149. /// %t = Thread ID
  150. /// %m = Message
  151. class DLL_LINKAGE CLogFormatter
  152. {
  153. public:
  154. CLogFormatter();
  155. CLogFormatter(const std::string & pattern);
  156. void setPattern(const std::string & pattern);
  157. const std::string & getPattern() const;
  158. std::string format(const LogRecord & record) const;
  159. private:
  160. std::string pattern;
  161. };
  162. /// The interface ILogTarget is used by all log target implementations. It holds
  163. /// the abstract method write which sub-classes should implement.
  164. class DLL_LINKAGE ILogTarget : public boost::noncopyable
  165. {
  166. public:
  167. virtual ~ILogTarget() { };
  168. virtual void write(const LogRecord & record) = 0;
  169. };
  170. /// The class CColorMapping maps a logger name and a level to a specific color. Supports domain inheritance.
  171. class DLL_LINKAGE CColorMapping
  172. {
  173. public:
  174. CColorMapping();
  175. void setColorFor(const CLoggerDomain & domain, ELogLevel::ELogLevel level, EConsoleTextColor::EConsoleTextColor color);
  176. EConsoleTextColor::EConsoleTextColor getColorFor(const CLoggerDomain & domain, ELogLevel::ELogLevel level) const;
  177. private:
  178. std::map<std::string, std::map<ELogLevel::ELogLevel, EConsoleTextColor::EConsoleTextColor> > map;
  179. };
  180. /// The class CLogConsoleTarget is a logging target which writes message to the console.
  181. class DLL_LINKAGE CLogConsoleTarget : public ILogTarget
  182. {
  183. public:
  184. explicit CLogConsoleTarget(CConsoleHandler * console);
  185. bool isColoredOutputEnabled() const;
  186. void setColoredOutputEnabled(bool coloredOutputEnabled);
  187. ELogLevel::ELogLevel getThreshold() const;
  188. void setThreshold(ELogLevel::ELogLevel threshold);
  189. const CLogFormatter & getFormatter() const;
  190. void setFormatter(const CLogFormatter & formatter);
  191. const CColorMapping & getColorMapping() const;
  192. void setColorMapping(const CColorMapping & colorMapping);
  193. void write(const LogRecord & record);
  194. private:
  195. CConsoleHandler * console;
  196. ELogLevel::ELogLevel threshold;
  197. bool coloredOutputEnabled;
  198. CLogFormatter formatter;
  199. CColorMapping colorMapping;
  200. mutable boost::mutex mx;
  201. };
  202. /// The class CLogFileTarget is a logging target which writes messages to a log file.
  203. class DLL_LINKAGE CLogFileTarget : public ILogTarget
  204. {
  205. public:
  206. /// Constructs a CLogFileTarget and opens the file designated by filePath. If the append parameter is true, the file
  207. /// will be appended to. Otherwise the file designated by filePath will be truncated before being opened.
  208. explicit CLogFileTarget(const std::string & filePath, bool append = true);
  209. ~CLogFileTarget();
  210. const CLogFormatter & getFormatter() const;
  211. void setFormatter(const CLogFormatter & formatter);
  212. void write(const LogRecord & record);
  213. private:
  214. std::ofstream file;
  215. CLogFormatter formatter;
  216. mutable boost::mutex mx;
  217. };