CLogger.h 9.3 KB

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