log.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. /////////////////////////////////////////////////////////////////////////////
  2. // Name: log.h
  3. // Purpose: topic overview
  4. // Author: wxWidgets team
  5. // Licence: wxWindows licence
  6. /////////////////////////////////////////////////////////////////////////////
  7. /**
  8. @page overview_log Logging Overview
  9. @tableofcontents
  10. This is a general overview of logging classes provided by wxWidgets. The word
  11. logging here has a broad sense, including all of the program output, not only
  12. non-interactive messages. The logging facilities included in wxWidgets provide
  13. the base wxLog class which defines the standard interface for a @e log target
  14. as well as several standard implementations of it and a family of functions to
  15. use with them.
  16. First of all, no knowledge of wxLog classes is needed to use them. For this,
  17. you should only know about @ref group_funcmacro_log "wxLogXXX() functions".
  18. All of them have the same syntax as @e printf() or @e vprintf() , i.e. they
  19. take the format string as the first argument and respectively a variable number
  20. of arguments or a variable argument list pointer. Here are all of them:
  21. @li wxLogFatalError() which is like wxLogError(), but also terminates the program
  22. with the exit code 3 (using @e abort() standard function). Unlike for all
  23. the other logging functions, this function can't be overridden by a log
  24. target.
  25. @li wxLogError() is the function to use for error messages, i.e. the messages
  26. that must be shown to the user. The default processing is to pop up a
  27. message box to inform the user about it.
  28. @li wxLogWarning() for warnings. They are also normally shown to the user, but
  29. don't interrupt the program work.
  30. @li wxLogMessage() is for all normal, informational messages. They also appear in
  31. a message box by default (but it can be changed, see below).
  32. @li wxLogVerbose() is for verbose output. Normally, it is suppressed, but might
  33. be activated if the user wishes to know more details about the program
  34. progress (another, but possibly confusing name for the same function is
  35. wxLogInfo).
  36. @li wxLogStatus() is for status messages. They will go into the status bar of the
  37. active or specified (as the first argument) wxFrame if it has one.
  38. @li wxLogSysError() is mostly used by wxWidgets itself, but might be handy for
  39. logging errors after system call (API function) failure. It logs the
  40. specified message text as well as the last system error code (@e errno or
  41. Windows' @e GetLastError() depending on the platform) and the corresponding error
  42. message. The second form of this function takes the error code explicitly
  43. as the first argument.
  44. @li wxLogDebug() is @b the right function for debug output. It only does anything
  45. at all in the debug mode (when the preprocessor symbol @c __WXDEBUG__ is
  46. defined) and expands to nothing in release mode (otherwise).
  47. Note that under Windows, you must either run the program under debugger or
  48. use a 3rd party program such as DebugView
  49. (http://www.microsoft.com/technet/sysinternals/Miscellaneous/DebugView.mspx)
  50. to actually see the debug output.
  51. @li wxLogTrace() as wxLogDebug() only does something in debug build. The reason for
  52. making it a separate function from it is that usually there are a lot of
  53. trace messages, so it might make sense to separate them from other debug
  54. messages which would be flooded in them. Moreover, the second version of
  55. this function takes a trace mask as the first argument which allows to
  56. further restrict the amount of messages generated.
  57. @see @ref group_funcmacro_log "Logging Functions and Macros"
  58. The usage of these functions should be fairly straightforward, however it may
  59. be asked why not use the other logging facilities, such as C standard stdio
  60. functions or C++ streams. The short answer is that they're all very good
  61. generic mechanisms, but are not really adapted for wxWidgets, while the log
  62. classes are. Some of advantages in using wxWidgets log functions are:
  63. @li @b Portability: It is a common practice to use @e printf() statements or
  64. cout/cerr C++ streams for writing out some (debug or otherwise)
  65. information. Although it works just fine under Unix, these messages go
  66. strictly nowhere under Windows where the stdout of GUI programs is not
  67. assigned to anything. Thus, you might view wxLogMessage() as a simple
  68. substitute for @e printf().
  69. You can also redirect the @e wxLogXXX calls to @e cout by just writing:
  70. @code
  71. wxLog* logger = new wxLogStream(&cout);
  72. wxLog::SetActiveTarget(logger);
  73. @endcode
  74. Finally, there is also a possibility to redirect the output sent to @e cout
  75. to a wxTextCtrl by using the wxStreamToTextRedirector class.
  76. @li @b Flexibility: The output of wxLog functions can be redirected or
  77. suppressed entirely based on their importance, which is either impossible
  78. or difficult to do with traditional methods. For example, only error
  79. messages, or only error messages and warnings might be logged, filtering
  80. out all informational messages.
  81. @li @b Completeness: Usually, an error message should be presented to the user
  82. when some operation fails. Let's take a quite simple but common case of a
  83. file error: suppose that you're writing your data file on disk and there is
  84. not enough space. The actual error might have been detected inside
  85. wxWidgets code (say, in wxFile::Write), so the calling function doesn't
  86. really know the exact reason of the failure, it only knows that the data
  87. file couldn't be written to the disk. However, as wxWidgets uses
  88. wxLogError() in this situation, the exact error code (and the corresponding
  89. error message) will be given to the user together with "high level" message
  90. about data file writing error.
  91. @section overview_log_enable Log Messages Selection
  92. By default, most log messages are enabled. In particular, this means that
  93. errors logged by wxWidgets code itself (e.g. when it fails to perform some
  94. operation, for instance wxFile::Open() logs an error when it fails to open a
  95. file) will be processed and shown to the user. To disable the logging entirely
  96. you can use wxLog::EnableLogging() method or, more usually, wxLogNull class
  97. which temporarily disables logging and restores it back to the original setting
  98. when it is destroyed.
  99. To limit logging to important messages only, you may use wxLog::SetLogLevel()
  100. with e.g. wxLOG_Warning value -- this will completely disable all logging
  101. messages with the severity less than warnings, so wxLogMessage() output won't
  102. be shown to the user any more.
  103. Moreover, the log level can be set separately for different log components.
  104. Before showing how this can be useful, let us explain what log components are:
  105. they are simply arbitrary strings identifying the component, or module, which
  106. generated the message. They are hierarchical in the sense that "foo/bar/baz"
  107. component is supposed to be a child of "foo". And all components are children
  108. of the unnamed root component.
  109. By default, all messages logged by wxWidgets originate from "wx" component or
  110. one of its subcomponents such as "wx/net/ftp", while the messages logged by
  111. your own code are assigned empty log component. To change this, you need to
  112. define @c wxLOG_COMPONENT to a string uniquely identifying each component, e.g.
  113. you could give it the value "MyProgram" by default and re-define it as
  114. "MyProgram/DB" in the module working with the database and "MyProgram/DB/Trans"
  115. in its part managing the transactions. Then you could use
  116. wxLog::SetComponentLevel() in the following ways:
  117. @code
  118. // disable all database error messages, everybody knows databases never
  119. // fail anyhow
  120. wxLog::SetComponentLevel("MyProgram/DB", wxLOG_FatalError);
  121. // but enable tracing for the transactions as somehow our changes don't
  122. // get committed sometimes
  123. wxLog::SetComponentLevel("MyProgram/DB/Trans", wxLOG_Trace);
  124. // also enable tracing messages from wxWidgets dynamic module loading
  125. // mechanism
  126. wxLog::SetComponentLevel("wx/base/module", wxLOG_Trace);
  127. @endcode
  128. Notice that the log level set explicitly for the transactions code overrides
  129. the log level of the parent component but that all other database code
  130. subcomponents inherit its setting by default and so won't generate any log
  131. messages at all.
  132. @section overview_log_targets Log Targets
  133. After having enumerated all the functions which are normally used to log the
  134. messages, and why would you want to use them, we now describe how all this
  135. works.
  136. wxWidgets has the notion of a <em>log target</em>: it is just a class deriving
  137. from wxLog. As such, it implements the virtual functions of the base class
  138. which are called when a message is logged. Only one log target is @e active at
  139. any moment, this is the one used by @ref group_funcmacro_log "wxLogXXX() functions".
  140. The normal usage of a log object (i.e. object of a class derived from wxLog) is
  141. to install it as the active target with a call to @e SetActiveTarget() and it
  142. will be used automatically by all subsequent calls to
  143. @ref group_funcmacro_log "wxLogXXX() functions".
  144. To create a new log target class you only need to derive it from wxLog and
  145. override one or several of wxLog::DoLogRecord(), wxLog::DoLogTextAtLevel() and
  146. wxLog::DoLogText() in it. The first one is the most flexible and allows you to
  147. change the formatting of the messages, dynamically filter and redirect them and
  148. so on -- all log messages, except for those generated by wxLogFatalError(),
  149. pass by this function. wxLog::DoLogTextAtLevel() should be overridden if you
  150. simply want to redirect the log messages somewhere else, without changing their
  151. formatting. Finally, it is enough to override wxLog::DoLogText() if you only
  152. want to redirect the log messages and the destination doesn't depend on the
  153. message log level.
  154. There are some predefined classes deriving from wxLog and which might be
  155. helpful to see how you can create a new log target class and, of course, may
  156. also be used without any change. There are:
  157. @li wxLogStderr: This class logs messages to a <tt>FILE *</tt>, using stderr by
  158. default as its name suggests.
  159. @li wxLogStream: This class has the same functionality as wxLogStderr, but uses
  160. @e ostream and cerr instead of <tt>FILE *</tt> and stderr.
  161. @li wxLogGui: This is the standard log target for wxWidgets applications (it is
  162. used by default if you don't do anything) and provides the most reasonable
  163. handling of all types of messages for given platform.
  164. @li wxLogWindow: This log target provides a "log console" which collects all
  165. messages generated by the application and also passes them to the previous
  166. active log target. The log window frame has a menu allowing user to clear
  167. the log, close it completely or save all messages to file.
  168. @li wxLogBuffer: This target collects all the logged messages in an internal
  169. buffer allowing to show them later to the user all at once.
  170. @li wxLogNull: The last log class is quite particular: it doesn't do anything.
  171. The objects of this class may be instantiated to (temporarily) suppress
  172. output of @e wxLogXXX() functions. As an example, trying to open a
  173. non-existing file will usually provoke an error message, but if for some
  174. reasons it is unwanted, just use this construction:
  175. @code
  176. wxFile file;
  177. // wxFile.Open() normally complains if file can't be opened, we don't want it
  178. {
  179. wxLogNull logNo;
  180. if ( !file.Open("bar") )
  181. {
  182. // ... process error ourselves ...
  183. }
  184. } // ~wxLogNull called, old log sink restored
  185. wxLogMessage("..."); // ok
  186. @endcode
  187. @see @ref group_class_logging "Logging Classes"
  188. The log targets can also be combined: for example you may wish to redirect the
  189. messages somewhere else (for example, to a log file) but also process them as
  190. normally. For this the wxLogChain, wxLogInterposer, and wxLogInterposerTemp can
  191. be used.
  192. @section overview_log_mt Logging in Multi-Threaded Applications
  193. Starting with wxWidgets 2.9.1, logging functions can be safely called from any
  194. thread. Messages logged from threads other than the main one will be buffered
  195. until wxLog::Flush() is called in the main thread (which usually happens during
  196. idle time, i.e. after processing all pending events) and will be really output
  197. only then. Notice that the default GUI logger already only output the messages
  198. when it is flushed, so by default messages from the other threads will be shown
  199. more or less at the same moment as usual. However if you define a custom log
  200. target, messages may be logged out of order, e.g. messages from the main thread
  201. with later timestamp may appear before messages with earlier timestamp logged
  202. from other threads. wxLog does however guarantee that messages logged by each
  203. thread will appear in order in which they were logged.
  204. Also notice that wxLog::EnableLogging() and wxLogNull class which uses it only
  205. affect the current thread, i.e. logging messages may still be generated by the
  206. other threads after a call to @c EnableLogging(false).
  207. @section overview_log_customize Logging Customization
  208. To completely change the logging behaviour you may define a custom log target.
  209. For example, you could define a class inheriting from wxLog which shows all the
  210. log messages in some part of your main application window reserved for the
  211. message output without interrupting the user work flow with modal message
  212. boxes.
  213. To use your custom log target you may either call wxLog::SetActiveTarget() with
  214. your custom log object or create a wxAppTraits-derived class and override
  215. wxAppTraits::CreateLogTarget() virtual method in it and also override wxApp::CreateTraits()
  216. to return an instance of your custom traits object. Notice that in the latter
  217. case you should be prepared for logging messages early during the program
  218. startup and also during program shutdown so you shouldn't rely on existence of
  219. the main application window, for example. You can however safely assume that
  220. GUI is (already/still) available when your log target as used as wxWidgets
  221. automatically switches to using wxLogStderr if it isn't.
  222. There are several methods which may be overridden in the derived class to
  223. customize log messages handling: wxLog::DoLogRecord(), wxLog::DoLogTextAtLevel()
  224. and wxLog::DoLogText().
  225. The last method is the simplest one: you should override it if you simply
  226. want to redirect the log output elsewhere, without taking into account the
  227. level of the message. If you do want to handle messages of different levels
  228. differently, then you should override wxLog::DoLogTextAtLevel().
  229. Additionally, you can customize the way full log messages are constructed from
  230. the components (such as time stamp, source file information, logging thread ID
  231. and so on). This task is performed by wxLogFormatter class so you need to
  232. derive a custom class from it and override its Format() method to build the log
  233. messages in desired way. Notice that if you just need to modify (or suppress)
  234. the time stamp display, overriding FormatTime() is enough.
  235. Finally, if even more control over the output format is needed, then
  236. DoLogRecord() can be overridden as it allows to construct custom messages
  237. depending on the log level or even do completely different things depending
  238. on the message severity (for example, throw away all messages except
  239. warnings and errors, show warnings on the screen and forward the error
  240. messages to the user's (or programmer's) cell phone -- maybe depending on
  241. whether the timestamp tells us if it is day or night in the current time
  242. zone).
  243. The @e dialog sample illustrates this approach by defining a custom log target
  244. customizing the dialog used by wxLogGui for the single messages.
  245. @section overview_log_tracemasks Using Trace Masks
  246. Notice that the use of log trace masks is hardly necessary any longer in
  247. current wxWidgets version as the same effect can be achieved by using
  248. different log components for different log statements of any level. Please
  249. see @ref overview_log_enable for more information about the log components.
  250. The functions below allow some limited customization of wxLog behaviour
  251. without writing a new log target class (which, aside from being a matter of
  252. several minutes, allows you to do anything you want).
  253. The verbose messages are the trace messages which are not disabled in the
  254. release mode and are generated by wxLogVerbose().
  255. They are not normally shown to the user because they present little interest,
  256. but may be activated, for example, in order to help the user find some program
  257. problem.
  258. As for the (real) trace messages, their handling depends on the currently
  259. enabled trace masks: if wxLog::AddTraceMask() was called for the mask of the given
  260. message, it will be logged, otherwise nothing happens.
  261. For example,
  262. @code
  263. wxLogTrace( wxTRACE_OleCalls, "IFoo::Bar() called" );
  264. @endcode
  265. will log the message if it was preceded by:
  266. @code
  267. wxLog::AddTraceMask( wxTRACE_OleCalls );
  268. @endcode
  269. The standard trace masks are given in wxLogTrace() documentation.
  270. */