2
0

CLogger.h 9.3 KB

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