CLogger.h 9.3 KB

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