CLogger.h 9.2 KB

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