2
0

CLogger.h 9.0 KB

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