logger.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. // Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #ifndef __LOGGER_H
  15. #define __LOGGER_H
  16. #include <cassert>
  17. #include <cstdlib>
  18. #include <string>
  19. #include <cstring>
  20. #include <exceptions/exceptions.h>
  21. #include <log/logger_level.h>
  22. #include <log/message_types.h>
  23. #include <log/log_formatter.h>
  24. namespace isc {
  25. namespace log {
  26. /// \page LoggingApi Logging API
  27. /// \section LoggingApiOverview Overview
  28. /// BIND 10 logging uses the concepts of the widely-used Java logging
  29. /// package log4j (http://logging.apache.log/log4j), albeit implemented
  30. /// in C++ using an open-source port. Features of the system are:
  31. ///
  32. /// - Within the code objects - known as loggers - can be created and
  33. /// used to log messages. These loggers have names; those with the
  34. /// same name share characteristics (such as output destination).
  35. /// - Loggers have a hierarchical relationship, with each logger being
  36. /// the child of another logger, except for the top of the hierarchy, the
  37. /// root logger. If a logger does not log a message, it is passed to the
  38. /// parent logger.
  39. /// - Messages can be logged at severity levels of FATAL, ERROR, WARN, INFO
  40. /// or DEBUG. The DEBUG level has further sub-levels numbered 0 (least
  41. /// informative) to 99 (most informative).
  42. /// - Each logger has a severity level set associated with it. When a
  43. /// message is logged, it is output only if it is logged at a level equal
  44. /// to the logger severity level or greater, e.g. if the logger's severity
  45. /// is WARN, only messages logged at WARN, ERROR or FATAL will be output.
  46. ///
  47. /// \section LoggingApiLoggerNames BIND 10 Logger Names
  48. /// Within BIND 10, the root logger root logger is given the name of the
  49. /// program (via the stand-alone function setRootLoggerName()). Other loggers
  50. /// are children of the root logger and are named "<program>.<sublogger>".
  51. /// This name appears in logging output, allowing users to identify both
  52. /// the BIND 10 program and the component within the program that generated
  53. /// the message.
  54. ///
  55. /// When creating a logger, the abbreviated name "<sublogger>" can be used;
  56. /// the program name will be prepended to it when the logger is created.
  57. /// In this way, individual libraries can have their own loggers without
  58. /// worrying about the program in which they are used, but:
  59. /// - The origin of the message will be clearly identified.
  60. /// - The same component can have different options (e.g. logging severity)
  61. /// in different programs at the same time.
  62. ///
  63. /// \section LoggingApiLoggingMessages Logging Messages
  64. /// Instead of embedding the text of messages within the code, each message
  65. /// is referred to using a symbolic name. The logging code uses this name as
  66. /// a key in a dictionary from which the message text is obtained. Such a
  67. /// system allows for the optional replacement of message text at run time.
  68. /// More details about the message disction (and the compiler used to create
  69. /// the symbol definitions) can be found in other modules in the src/lib/log
  70. /// directory.
  71. class LoggerImpl; // Forward declaration of the implementation class
  72. /// \brief Logging Not Initialized
  73. ///
  74. /// Exception thrown if an attempt is made to access a logging function
  75. /// if the logging system has not been initialized.
  76. class LoggingNotInitialized : public isc::Exception {
  77. public:
  78. LoggingNotInitialized(const char* file, size_t line, const char* what) :
  79. isc::Exception(file, line, what)
  80. {}
  81. };
  82. /// \brief Logger Class
  83. ///
  84. /// This class is the main class used for logging. Use comprises:
  85. ///
  86. /// 1. Constructing a logger by instantiating it with a specific name. (If the
  87. /// same logger is in multiple functions within a file, overhead can be
  88. /// minimised by declaring it as a file-wide static variable.)
  89. /// 2. Using the error(), info() etc. methods to log an error. (However, it is
  90. /// recommended to use the LOG_ERROR, LOG_INFO etc. macros defined in macros.h.
  91. /// These will avoid the potentially-expensive evaluation of arguments if the
  92. /// severity is such that the message will be suppressed.)
  93. class Logger {
  94. public:
  95. enum {
  96. MAX_LOGGER_NAME_SIZE = 32 ///< Maximum size of logger name
  97. };
  98. /// \brief Constructor
  99. ///
  100. /// Creates/attaches to a logger of a specific name.
  101. ///
  102. /// \param name Name of the logger. If the name is that of the root name,
  103. /// this creates an instance of the root logger; otherwise it creates a
  104. /// child of the root logger.
  105. ///
  106. /// \note The name of the logger may be no longer than MAX_LOGGER_NAME_SIZE
  107. /// else the program will halt with an assertion failure. This restriction
  108. /// allows loggers to be declared statically: the name is stored in a
  109. /// fixed-size array to avoid the need to allocate heap storage during
  110. /// program initialization (which causes problems on some operating
  111. /// systems).
  112. ///
  113. /// \note Note also that there is no constructor taking a std::string. This
  114. /// minimises the possibility of initializing a static logger with a
  115. /// string, so leading to problems mentioned above.
  116. Logger(const char* name) : loggerptr_(NULL) {
  117. assert(std::strlen(name) < sizeof(name_));
  118. std::strcpy(name_, name);
  119. }
  120. /// \brief Destructor
  121. virtual ~Logger();
  122. /// \brief The formatter used to replace placeholders
  123. typedef isc::log::Formatter<Logger> Formatter;
  124. /// \brief Get Name of Logger
  125. ///
  126. /// \return The full name of the logger (including the root name)
  127. virtual std::string getName();
  128. /// \brief Set Severity Level for Logger
  129. ///
  130. /// Sets the level at which this logger will log messages. If none is set,
  131. /// the level is inherited from the parent.
  132. ///
  133. /// \param severity Severity level to log
  134. /// \param dbglevel If the severity is DEBUG, this is the debug level.
  135. /// This can be in the range 1 to 100 and controls the verbosity. A value
  136. /// outside these limits is silently coerced to the nearest boundary.
  137. virtual void setSeverity(isc::log::Severity severity, int dbglevel = 1);
  138. /// \brief Get Severity Level for Logger
  139. ///
  140. /// \return The current logging level of this logger. In most cases though,
  141. /// the effective logging level is what is required.
  142. virtual isc::log::Severity getSeverity();
  143. /// \brief Get Effective Severity Level for Logger
  144. ///
  145. /// \return The effective severity level of the logger. This is the same
  146. /// as getSeverity() if the logger has a severity level set, but otherwise
  147. /// is the severity of the parent.
  148. virtual isc::log::Severity getEffectiveSeverity();
  149. /// \brief Return DEBUG Level
  150. ///
  151. /// \return Current setting of debug level. This is returned regardless of
  152. /// whether the severity is set to debug.
  153. virtual int getDebugLevel();
  154. /// \brief Get Effective Debug Level for Logger
  155. ///
  156. /// \return The effective debug level of the logger. This is the same
  157. /// as getDebugLevel() if the logger has a debug level set, but otherwise
  158. /// is the debug level of the parent.
  159. virtual int getEffectiveDebugLevel();
  160. /// \brief Returns if Debug Message Should Be Output
  161. ///
  162. /// \param dbglevel Level for which debugging is checked. Debugging is
  163. /// enabled only if the logger has DEBUG enabled and if the dbglevel
  164. /// checked is less than or equal to the debug level set for the logger.
  165. virtual bool isDebugEnabled(int dbglevel = MIN_DEBUG_LEVEL);
  166. /// \brief Is INFO Enabled?
  167. virtual bool isInfoEnabled();
  168. /// \brief Is WARNING Enabled?
  169. virtual bool isWarnEnabled();
  170. /// \brief Is ERROR Enabled?
  171. virtual bool isErrorEnabled();
  172. /// \brief Is FATAL Enabled?
  173. virtual bool isFatalEnabled();
  174. /// \brief Output Debug Message
  175. ///
  176. /// \param dbglevel Debug level, ranging between 0 and 99. Higher numbers
  177. /// are used for more verbose output.
  178. /// \param ident Message identification.
  179. Formatter debug(int dbglevel, const MessageID& ident);
  180. /// \brief Output Informational Message
  181. ///
  182. /// \param ident Message identification.
  183. Formatter info(const MessageID& ident);
  184. /// \brief Output Warning Message
  185. ///
  186. /// \param ident Message identification.
  187. Formatter warn(const MessageID& ident);
  188. /// \brief Output Error Message
  189. ///
  190. /// \param ident Message identification.
  191. Formatter error(const MessageID& ident);
  192. /// \brief Output Fatal Message
  193. ///
  194. /// \param ident Message identification.
  195. Formatter fatal(const MessageID& ident);
  196. /// \brief Equality
  197. ///
  198. /// Check if two instances of this logger refer to the same stream.
  199. ///
  200. /// \return true if the logger objects are instances of the same logger.
  201. bool operator==(Logger& other);
  202. private:
  203. friend class isc::log::Formatter<Logger>;
  204. /// \brief Raw output function
  205. ///
  206. /// This is used by the formatter to output formatted output.
  207. ///
  208. /// \param severity Severity of the message being output.
  209. /// \param message Text of the message to be output.
  210. void output(const Severity& severity, const std::string& message);
  211. /// \brief Copy Constructor
  212. ///
  213. /// Disabled (marked private) as it makes no sense to copy the logger -
  214. /// just create another one of the same name.
  215. Logger(const Logger&);
  216. /// \brief Assignment Operator
  217. ///
  218. /// Disabled (marked private) as it makes no sense to copy the logger -
  219. /// just create another one of the same name.
  220. Logger& operator=(const Logger&);
  221. /// \brief Initialize Implementation
  222. ///
  223. /// Returns the logger pointer. If not yet set, the implementation class is
  224. /// initialized.
  225. ///
  226. /// The main reason for this is to allow loggers to be declared statically
  227. /// before the underlying logging system is initialized. However, any
  228. /// attempt to access a logging method on any logger before initialization -
  229. /// regardless of whether is is statically or automatically declared - will
  230. /// cause a "LoggingNotInitialized" exception to be thrown.
  231. ///
  232. /// \return Returns pointer to implementation
  233. LoggerImpl* getLoggerPtr() {
  234. if (!loggerptr_) {
  235. initLoggerImpl();
  236. }
  237. return (loggerptr_);
  238. }
  239. /// \brief Initialize Underlying Implementation and Set loggerptr_
  240. void initLoggerImpl();
  241. LoggerImpl* loggerptr_; ///< Pointer to underlying logger
  242. char name_[MAX_LOGGER_NAME_SIZE]; ///< Copy of the logger name
  243. };
  244. } // namespace log
  245. } // namespace isc
  246. #endif // __LOGGER_H