logger.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. #include <util/interprocess_sync.h>
  25. namespace isc {
  26. namespace log {
  27. /// \page LoggingApi Logging API
  28. /// \section LoggingApiOverview Overview
  29. /// BIND 10 logging uses the concepts of the widely-used Java logging
  30. /// package log4j (http://logging.apache.log/log4j), albeit implemented
  31. /// in C++ using an open-source port. Features of the system are:
  32. ///
  33. /// - Within the code objects - known as loggers - can be created and
  34. /// used to log messages. These loggers have names; those with the
  35. /// same name share characteristics (such as output destination).
  36. /// - Loggers have a hierarchical relationship, with each logger being
  37. /// the child of another logger, except for the top of the hierarchy, the
  38. /// root logger. If a logger does not log a message, it is passed to the
  39. /// parent logger.
  40. /// - Messages can be logged at severity levels of FATAL, ERROR, WARN, INFO
  41. /// or DEBUG. The DEBUG level has further sub-levels numbered 0 (least
  42. /// informative) to 99 (most informative).
  43. /// - Each logger has a severity level set associated with it. When a
  44. /// message is logged, it is output only if it is logged at a level equal
  45. /// to the logger severity level or greater, e.g. if the logger's severity
  46. /// is WARN, only messages logged at WARN, ERROR or FATAL will be output.
  47. ///
  48. /// \section LoggingApiLoggerNames BIND 10 Logger Names
  49. /// Within BIND 10, the root logger root logger is given the name of the
  50. /// program (via the stand-alone function setRootLoggerName()). Other loggers
  51. /// are children of the root logger and are named "<program>.<sublogger>".
  52. /// This name appears in logging output, allowing users to identify both
  53. /// the BIND 10 program and the component within the program that generated
  54. /// the message.
  55. ///
  56. /// When creating a logger, the abbreviated name "<sublogger>" can be used;
  57. /// the program name will be prepended to it when the logger is created.
  58. /// In this way, individual libraries can have their own loggers without
  59. /// worrying about the program in which they are used, but:
  60. /// - The origin of the message will be clearly identified.
  61. /// - The same component can have different options (e.g. logging severity)
  62. /// in different programs at the same time.
  63. ///
  64. /// \section LoggingApiLoggingMessages Logging Messages
  65. /// Instead of embedding the text of messages within the code, each message
  66. /// is referred to using a symbolic name. The logging code uses this name as
  67. /// a key in a dictionary from which the message text is obtained. Such a
  68. /// system allows for the optional replacement of message text at run time.
  69. /// More details about the message dictionary (and the compiler used to create
  70. /// the symbol definitions) can be found in other modules in the src/lib/log
  71. /// directory.
  72. ///
  73. /// \section LoggingApiImplementationIssues Implementation Issues
  74. /// Owing to the way that the logging is implemented, notably that loggers can
  75. /// be declared as static external objects, there is a restriction on the
  76. /// length of the name of a logger component (i.e. the length of
  77. /// the string passed to the Logger constructor) to a maximum of 31 characters.
  78. /// There is no reason for this particular value other than limiting the amount
  79. /// of memory used. It is defined by the constant Logger::MAX_LOGGER_NAME_SIZE,
  80. /// and can be made larger (or smaller) if so desired. Note however, using a
  81. /// logger name larger than this limit will cause an assertion failure.
  82. class LoggerImpl; // Forward declaration of the implementation class
  83. /// \brief Logging Not Initialized
  84. ///
  85. /// Exception thrown if an attempt is made to access a logging function
  86. /// if the logging system has not been initialized.
  87. class LoggingNotInitialized : public isc::Exception {
  88. public:
  89. LoggingNotInitialized(const char* file, size_t line, const char* what) :
  90. isc::Exception(file, line, what)
  91. {}
  92. };
  93. /// \brief Bad Interprocess Sync
  94. ///
  95. /// Exception thrown if a bad InterprocessSync object (such as NULL) is
  96. /// used.
  97. class BadInterprocessSync : public isc::Exception {
  98. public:
  99. BadInterprocessSync(const char* file, size_t line, const char* what) :
  100. isc::Exception(file, line, what)
  101. {}
  102. };
  103. /// \brief Logger Class
  104. ///
  105. /// This class is the main class used for logging. Use comprises:
  106. ///
  107. /// 1. Constructing a logger by instantiating it with a specific name. (If the
  108. /// same logger is in multiple functions within a file, overhead can be
  109. /// minimised by declaring it as a file-wide static variable.)
  110. /// 2. Using the error(), info() etc. methods to log an error. (However, it is
  111. /// recommended to use the LOG_ERROR, LOG_INFO etc. macros defined in macros.h.
  112. /// These will avoid the potentially-expensive evaluation of arguments if the
  113. /// severity is such that the message will be suppressed.)
  114. class Logger {
  115. public:
  116. /// Maximum size of a logger name
  117. static const size_t MAX_LOGGER_NAME_SIZE = 31;
  118. /// \brief Constructor
  119. ///
  120. /// Creates/attaches to a logger of a specific name.
  121. ///
  122. /// \param name Name of the logger. If the name is that of the root name,
  123. /// this creates an instance of the root logger; otherwise it creates a
  124. /// child of the root logger.
  125. ///
  126. /// \note The name of the logger may be no longer than MAX_LOGGER_NAME_SIZE
  127. /// else the program will halt with an assertion failure. This restriction
  128. /// allows loggers to be declared statically: the name is stored in a
  129. /// fixed-size array to avoid the need to allocate heap storage during
  130. /// program initialization (which causes problems on some operating
  131. /// systems).
  132. ///
  133. /// \note Note also that there is no constructor taking a std::string. This
  134. /// minimises the possibility of initializing a static logger with a
  135. /// string, so leading to problems mentioned above.
  136. Logger(const char* name) : loggerptr_(NULL) {
  137. assert(std::strlen(name) < sizeof(name_));
  138. // Do the copy. Note that the assertion above has checked that the
  139. // contents of "name" and a trailing null will fit within the space
  140. // allocated for name_, so we could use strcpy here and be safe.
  141. // However, a bit of extra paranoia doesn't hurt.
  142. std::strncpy(name_, name, sizeof(name_));
  143. assert(name_[sizeof(name_) - 1] == '\0');
  144. }
  145. /// \brief Destructor
  146. virtual ~Logger();
  147. /// \brief The formatter used to replace placeholders
  148. typedef isc::log::Formatter<Logger> Formatter;
  149. /// \brief Get Name of Logger
  150. ///
  151. /// \return The full name of the logger (including the root name)
  152. virtual std::string getName();
  153. /// \brief Set Severity Level for Logger
  154. ///
  155. /// Sets the level at which this logger will log messages. If none is set,
  156. /// the level is inherited from the parent.
  157. ///
  158. /// \param severity Severity level to log
  159. /// \param dbglevel If the severity is DEBUG, this is the debug level.
  160. /// This can be in the range 1 to 100 and controls the verbosity. A value
  161. /// outside these limits is silently coerced to the nearest boundary.
  162. virtual void setSeverity(isc::log::Severity severity, int dbglevel = 1);
  163. /// \brief Get Severity Level for Logger
  164. ///
  165. /// \return The current logging level of this logger. In most cases though,
  166. /// the effective logging level is what is required.
  167. virtual isc::log::Severity getSeverity();
  168. /// \brief Get Effective Severity Level for Logger
  169. ///
  170. /// \return The effective severity level of the logger. This is the same
  171. /// as getSeverity() if the logger has a severity level set, but otherwise
  172. /// is the severity of the parent.
  173. virtual isc::log::Severity getEffectiveSeverity();
  174. /// \brief Return DEBUG Level
  175. ///
  176. /// \return Current setting of debug level. This is returned regardless of
  177. /// whether the severity is set to debug.
  178. virtual int getDebugLevel();
  179. /// \brief Get Effective Debug Level for Logger
  180. ///
  181. /// \return The effective debug level of the logger. This is the same
  182. /// as getDebugLevel() if the logger has a debug level set, but otherwise
  183. /// is the debug level of the parent.
  184. virtual int getEffectiveDebugLevel();
  185. /// \brief Returns if Debug Message Should Be Output
  186. ///
  187. /// \param dbglevel Level for which debugging is checked. Debugging is
  188. /// enabled only if the logger has DEBUG enabled and if the dbglevel
  189. /// checked is less than or equal to the debug level set for the logger.
  190. virtual bool isDebugEnabled(int dbglevel = MIN_DEBUG_LEVEL);
  191. /// \brief Is INFO Enabled?
  192. virtual bool isInfoEnabled();
  193. /// \brief Is WARNING Enabled?
  194. virtual bool isWarnEnabled();
  195. /// \brief Is ERROR Enabled?
  196. virtual bool isErrorEnabled();
  197. /// \brief Is FATAL Enabled?
  198. virtual bool isFatalEnabled();
  199. /// \brief Output Debug Message
  200. ///
  201. /// \param dbglevel Debug level, ranging between 0 and 99. Higher numbers
  202. /// are used for more verbose output.
  203. /// \param ident Message identification.
  204. Formatter debug(int dbglevel, const MessageID& ident);
  205. /// \brief Output Informational Message
  206. ///
  207. /// \param ident Message identification.
  208. Formatter info(const MessageID& ident);
  209. /// \brief Output Warning Message
  210. ///
  211. /// \param ident Message identification.
  212. Formatter warn(const MessageID& ident);
  213. /// \brief Output Error Message
  214. ///
  215. /// \param ident Message identification.
  216. Formatter error(const MessageID& ident);
  217. /// \brief Output Fatal Message
  218. ///
  219. /// \param ident Message identification.
  220. Formatter fatal(const MessageID& ident);
  221. /// \brief Replace the interprocess synchronization object
  222. ///
  223. /// If this method is called with NULL as the argument, it throws a
  224. /// BadInterprocessSync exception.
  225. ///
  226. /// \param sync The logger uses this synchronization object for
  227. /// synchronizing output of log messages. It should be deletable and
  228. /// the ownership is transferred to the logger. If NULL is passed,
  229. /// a BadInterprocessSync exception is thrown.
  230. void setInterprocessSync(isc::util::InterprocessSync* sync);
  231. /// \brief Equality
  232. ///
  233. /// Check if two instances of this logger refer to the same stream.
  234. ///
  235. /// \return true if the logger objects are instances of the same logger.
  236. bool operator==(Logger& other);
  237. private:
  238. friend class isc::log::Formatter<Logger>;
  239. /// \brief Raw output function
  240. ///
  241. /// This is used by the formatter to output formatted output.
  242. ///
  243. /// \param severity Severity of the message being output.
  244. /// \param message Text of the message to be output.
  245. void output(const Severity& severity, const std::string& message);
  246. /// \brief Copy Constructor
  247. ///
  248. /// Disabled (marked private) as it makes no sense to copy the logger -
  249. /// just create another one of the same name.
  250. Logger(const Logger&);
  251. /// \brief Assignment Operator
  252. ///
  253. /// Disabled (marked private) as it makes no sense to copy the logger -
  254. /// just create another one of the same name.
  255. Logger& operator=(const Logger&);
  256. /// \brief Initialize Implementation
  257. ///
  258. /// Returns the logger pointer. If not yet set, the implementation class is
  259. /// initialized.
  260. ///
  261. /// The main reason for this is to allow loggers to be declared statically
  262. /// before the underlying logging system is initialized. However, any
  263. /// attempt to access a logging method on any logger before initialization -
  264. /// regardless of whether is is statically or automatically declared - will
  265. /// cause a "LoggingNotInitialized" exception to be thrown.
  266. ///
  267. /// \return Returns pointer to implementation
  268. LoggerImpl* getLoggerPtr() {
  269. if (!loggerptr_) {
  270. initLoggerImpl();
  271. }
  272. return (loggerptr_);
  273. }
  274. /// \brief Initialize Underlying Implementation and Set loggerptr_
  275. void initLoggerImpl();
  276. LoggerImpl* loggerptr_; ///< Pointer to underlying logger
  277. char name_[MAX_LOGGER_NAME_SIZE + 1]; ///< Copy of the logger name
  278. };
  279. } // namespace log
  280. } // namespace isc
  281. #endif // __LOGGER_H