]> git.saurik.com Git - wxWidgets.git/blob - include/wx/log.h
previous commit removed WXDLLIMPEXP_HTML by mistake
[wxWidgets.git] / include / wx / log.h
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: wx/log.h
3 // Purpose: Assorted wxLogXXX functions, and wxLog (sink for logs)
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 29/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifndef _WX_LOG_H_
13 #define _WX_LOG_H_
14
15 #if defined(__GNUG__) && !defined(__APPLE__)
16 #pragma interface "log.h"
17 #endif
18
19 #include "wx/defs.h"
20
21 #if wxUSE_LOG
22
23 #include "wx/string.h"
24 #include "wx/arrstr.h"
25
26 // ----------------------------------------------------------------------------
27 // forward declarations
28 // ----------------------------------------------------------------------------
29
30 #if wxUSE_GUI
31 class WXDLLIMPEXP_CORE wxTextCtrl;
32 class WXDLLIMPEXP_CORE wxLogFrame;
33 class WXDLLIMPEXP_CORE wxFrame;
34 #endif // wxUSE_GUI
35
36 // ----------------------------------------------------------------------------
37 // types
38 // ----------------------------------------------------------------------------
39
40 typedef unsigned long wxTraceMask;
41 typedef unsigned long wxLogLevel;
42
43 // ----------------------------------------------------------------------------
44 // headers
45 // ----------------------------------------------------------------------------
46
47 #ifndef __WXWINCE__
48 #include <time.h> // for time_t
49 #endif
50
51 #include "wx/dynarray.h"
52
53 #ifndef wxUSE_LOG_DEBUG
54 # ifdef __WXDEBUG__
55 # define wxUSE_LOG_DEBUG 1
56 # else // !__WXDEBUG__
57 # define wxUSE_LOG_DEBUG 0
58 # endif
59 #endif
60
61 // ----------------------------------------------------------------------------
62 // constants
63 // ----------------------------------------------------------------------------
64
65 // different standard log levels (you may also define your own)
66 enum
67 {
68 wxLOG_FatalError, // program can't continue, abort immediately
69 wxLOG_Error, // a serious error, user must be informed about it
70 wxLOG_Warning, // user is normally informed about it but may be ignored
71 wxLOG_Message, // normal message (i.e. normal output of a non GUI app)
72 wxLOG_Status, // informational: might go to the status line of GUI app
73 wxLOG_Info, // informational message (a.k.a. 'Verbose')
74 wxLOG_Debug, // never shown to the user, disabled in release mode
75 wxLOG_Trace, // trace messages are also only enabled in debug mode
76 wxLOG_Progress, // used for progress indicator (not yet)
77 wxLOG_User = 100, // user defined levels start here
78 wxLOG_Max = 10000
79 };
80
81 // symbolic trace masks - wxLogTrace("foo", "some trace message...") will be
82 // discarded unless the string "foo" has been added to the list of allowed
83 // ones with AddTraceMask()
84
85 #define wxTRACE_MemAlloc wxT("memalloc") // trace memory allocation (new/delete)
86 #define wxTRACE_Messages wxT("messages") // trace window messages/X callbacks
87 #define wxTRACE_ResAlloc wxT("resalloc") // trace GDI resource allocation
88 #define wxTRACE_RefCount wxT("refcount") // trace various ref counting operations
89
90 #ifdef __WXMSW__
91 #define wxTRACE_OleCalls wxT("ole") // OLE interface calls
92 #endif
93
94 // the trace masks have been superceded by symbolic trace constants, they're
95 // for compatibility only andwill be removed soon - do NOT use them
96
97 // meaning of different bits of the trace mask (which allows selectively
98 // enable/disable some trace messages)
99 #define wxTraceMemAlloc 0x0001 // trace memory allocation (new/delete)
100 #define wxTraceMessages 0x0002 // trace window messages/X callbacks
101 #define wxTraceResAlloc 0x0004 // trace GDI resource allocation
102 #define wxTraceRefCount 0x0008 // trace various ref counting operations
103
104 #ifdef __WXMSW__
105 #define wxTraceOleCalls 0x0100 // OLE interface calls
106 #endif
107
108 #include "wx/iosfwrap.h"
109
110 // ----------------------------------------------------------------------------
111 // derive from this class to redirect (or suppress, or ...) log messages
112 // normally, only a single instance of this class exists but it's not enforced
113 // ----------------------------------------------------------------------------
114
115 class WXDLLIMPEXP_BASE wxLog
116 {
117 public:
118 // ctor
119 wxLog();
120
121 // Internal buffer.
122 // Allow replacement of the fixed size static buffer with
123 // a user allocated one. Pass in NULL to restore the
124 // built in static buffer.
125 static wxChar *SetLogBuffer( wxChar *buf, size_t size = 0 );
126
127 // these functions allow to completely disable all log messages
128 // is logging disabled now?
129 static bool IsEnabled() { return ms_doLog; }
130 // change the flag state, return the previous one
131 static bool EnableLogging(bool doIt = TRUE)
132 { bool doLogOld = ms_doLog; ms_doLog = doIt; return doLogOld; }
133
134 // static sink function - see DoLog() for function to overload in the
135 // derived classes
136 static void OnLog(wxLogLevel level, const wxChar *szString, time_t t)
137 {
138 if ( IsEnabled() && ms_logLevel >= level ) {
139 wxLog *pLogger = GetActiveTarget();
140 if ( pLogger )
141 pLogger->DoLog(level, szString, t);
142 }
143 }
144
145 // message buffering
146 // flush shows all messages if they're not logged immediately (FILE
147 // and iostream logs don't need it, but wxGuiLog does to avoid showing
148 // 17 modal dialogs one after another)
149 virtual void Flush();
150
151 // flush the active target if any
152 static void FlushActive()
153 {
154 if ( !ms_suspendCount )
155 {
156 wxLog *log = GetActiveTarget();
157 if ( log )
158 log->Flush();
159 }
160 }
161
162 // only one sink is active at each moment
163 // get current log target, will call wxApp::CreateLogTarget() to
164 // create one if none exists
165 static wxLog *GetActiveTarget();
166 // change log target, pLogger may be NULL
167 static wxLog *SetActiveTarget(wxLog *pLogger);
168
169 // suspend the message flushing of the main target until the next call
170 // to Resume() - this is mainly for internal use (to prevent wxYield()
171 // from flashing the messages)
172 static void Suspend() { ms_suspendCount++; }
173 // must be called for each Suspend()!
174 static void Resume() { ms_suspendCount--; }
175
176 // functions controlling the default wxLog behaviour
177 // verbose mode is activated by standard command-line '-verbose'
178 // option
179 static void SetVerbose(bool bVerbose = TRUE) { ms_bVerbose = bVerbose; }
180
181 // Set log level. Log messages with level > logLevel will not be logged.
182 static void SetLogLevel(wxLogLevel logLevel) { ms_logLevel = logLevel; }
183
184 // should GetActiveTarget() try to create a new log object if the
185 // current is NULL?
186 static void DontCreateOnDemand();
187
188 // trace mask (see wxTraceXXX constants for details)
189 static void SetTraceMask(wxTraceMask ulMask) { ms_ulTraceMask = ulMask; }
190 // add string trace mask
191 static void AddTraceMask(const wxString& str)
192 { ms_aTraceMasks.push_back(str); }
193 // add string trace mask
194 static void RemoveTraceMask(const wxString& str);
195 // remove all string trace masks
196 static void ClearTraceMasks();
197 // get string trace masks
198 static const wxArrayString &GetTraceMasks() { return ms_aTraceMasks; }
199
200 // sets the timestamp string: this is used as strftime() format string
201 // for the log targets which add time stamps to the messages - set it
202 // to NULL to disable time stamping completely.
203 static void SetTimestamp(const wxChar *ts) { ms_timestamp = ts; }
204
205
206 // accessors
207 // gets the verbose status
208 static bool GetVerbose() { return ms_bVerbose; }
209 // get trace mask
210 static wxTraceMask GetTraceMask() { return ms_ulTraceMask; }
211 // is this trace mask in the list?
212 static bool IsAllowedTraceMask(const wxChar *mask);
213 // return the current loglevel limit
214 static wxLogLevel GetLogLevel() { return ms_logLevel; }
215
216 // get the current timestamp format string (may be NULL)
217 static const wxChar *GetTimestamp() { return ms_timestamp; }
218
219
220 // helpers
221 // put the time stamp into the string if ms_timestamp != NULL (don't
222 // change it otherwise)
223 static void TimeStamp(wxString *str);
224
225 // make dtor virtual for all derived classes
226 virtual ~wxLog() { }
227
228
229 // this method exists for backwards compatibility only, don't use
230 bool HasPendingMessages() const { return TRUE; }
231
232 protected:
233 // the logging functions that can be overriden
234 // default DoLog() prepends the time stamp and a prefix corresponding
235 // to the message to szString and then passes it to DoLogString()
236 virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t);
237 // default DoLogString does nothing but is not pure virtual because if
238 // you override DoLog() you might not need it at all
239 virtual void DoLogString(const wxChar *szString, time_t t);
240
241 private:
242 // static variables
243 // ----------------
244
245 static wxLog *ms_pLogger; // currently active log sink
246 static bool ms_doLog; // FALSE => all logging disabled
247 static bool ms_bAutoCreate; // create new log targets on demand?
248 static bool ms_bVerbose; // FALSE => ignore LogInfo messages
249
250 static wxLogLevel ms_logLevel; // limit logging to levels <= ms_logLevel
251
252 static size_t ms_suspendCount; // if positive, logs are not flushed
253
254 // format string for strftime(), if NULL, time stamping log messages is
255 // disabled
256 static const wxChar *ms_timestamp;
257
258 static wxTraceMask ms_ulTraceMask; // controls wxLogTrace behaviour
259 static wxArrayString ms_aTraceMasks; // more powerful filter for wxLogTrace
260 };
261
262 // ----------------------------------------------------------------------------
263 // "trivial" derivations of wxLog
264 // ----------------------------------------------------------------------------
265
266 // log everything to a "FILE *", stderr by default
267 class WXDLLIMPEXP_BASE wxLogStderr : public wxLog
268 {
269 DECLARE_NO_COPY_CLASS(wxLogStderr)
270
271 public:
272 // redirect log output to a FILE
273 wxLogStderr(FILE *fp = (FILE *) NULL);
274
275 protected:
276 // implement sink function
277 virtual void DoLogString(const wxChar *szString, time_t t);
278
279 FILE *m_fp;
280 };
281
282 #if wxUSE_STD_IOSTREAM
283
284 // log everything to an "ostream", cerr by default
285 class WXDLLIMPEXP_BASE wxLogStream : public wxLog
286 {
287 public:
288 // redirect log output to an ostream
289 wxLogStream(wxSTD ostream *ostr = (wxSTD ostream *) NULL);
290
291 protected:
292 // implement sink function
293 virtual void DoLogString(const wxChar *szString, time_t t);
294
295 // using ptr here to avoid including <iostream.h> from this file
296 wxSTD ostream *m_ostr;
297 };
298
299 #endif // wxUSE_STD_IOSTREAM
300
301 // ----------------------------------------------------------------------------
302 // /dev/null log target: suppress logging until this object goes out of scope
303 // ----------------------------------------------------------------------------
304
305 // example of usage:
306 /*
307 void Foo()
308 {
309 wxFile file;
310
311 // wxFile.Open() normally complains if file can't be opened, we don't
312 // want it
313 wxLogNull logNo;
314
315 if ( !file.Open("bar") )
316 ... process error ourselves ...
317
318 // ~wxLogNull called, old log sink restored
319 }
320 */
321 class WXDLLIMPEXP_BASE wxLogNull
322 {
323 public:
324 wxLogNull() : m_flagOld(wxLog::EnableLogging(FALSE)) { }
325 ~wxLogNull() { (void)wxLog::EnableLogging(m_flagOld); }
326
327 private:
328 bool m_flagOld; // the previous value of the wxLog::ms_doLog
329 };
330
331 // ----------------------------------------------------------------------------
332 // chaining log target: installs itself as a log target and passes all
333 // messages to the real log target given to it in the ctor but also forwards
334 // them to the previously active one
335 //
336 // note that you don't have to call SetActiveTarget() with this class, it
337 // does it itself in its ctor
338 // ----------------------------------------------------------------------------
339
340 class WXDLLIMPEXP_BASE wxLogChain : public wxLog
341 {
342 public:
343 wxLogChain(wxLog *logger);
344 virtual ~wxLogChain();
345
346 // change the new log target
347 void SetLog(wxLog *logger);
348
349 // this can be used to temporarily disable (and then reenable) passing
350 // messages to the old logger (by default we do pass them)
351 void PassMessages(bool bDoPass) { m_bPassMessages = bDoPass; }
352
353 // are we passing the messages to the previous log target?
354 bool IsPassingMessages() const { return m_bPassMessages; }
355
356 // return the previous log target (may be NULL)
357 wxLog *GetOldLog() const { return m_logOld; }
358
359 // override base class version to flush the old logger as well
360 virtual void Flush();
361
362 protected:
363 // pass the chain to the old logger if needed
364 virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t);
365
366 private:
367 // the current log target
368 wxLog *m_logNew;
369
370 // the previous log target
371 wxLog *m_logOld;
372
373 // do we pass the messages to the old logger?
374 bool m_bPassMessages;
375
376 DECLARE_NO_COPY_CLASS(wxLogChain)
377 };
378
379 // a chain log target which uses itself as the new logger
380 class WXDLLIMPEXP_BASE wxLogPassThrough : public wxLogChain
381 {
382 public:
383 wxLogPassThrough();
384 };
385
386 #if wxUSE_GUI
387 // include GUI log targets:
388 #include "wx/generic/logg.h"
389 #endif // wxUSE_GUI
390
391 // ============================================================================
392 // global functions
393 // ============================================================================
394
395 // ----------------------------------------------------------------------------
396 // Log functions should be used by application instead of stdio, iostream &c
397 // for log messages for easy redirection
398 // ----------------------------------------------------------------------------
399
400 // ----------------------------------------------------------------------------
401 // get error code/error message from system in a portable way
402 // ----------------------------------------------------------------------------
403
404 // return the last system error code
405 WXDLLIMPEXP_BASE unsigned long wxSysErrorCode();
406
407 // return the error message for given (or last if 0) error code
408 WXDLLIMPEXP_BASE const wxChar* wxSysErrorMsg(unsigned long nErrCode = 0);
409
410 // ----------------------------------------------------------------------------
411 // define wxLog<level>
412 // ----------------------------------------------------------------------------
413
414 #define DECLARE_LOG_FUNCTION(level) \
415 extern void WXDLLIMPEXP_BASE wxVLog##level(const wxChar *szFormat, \
416 va_list argptr); \
417 extern void WXDLLIMPEXP_BASE wxLog##level(const wxChar *szFormat, \
418 ...) ATTRIBUTE_PRINTF_1
419 #define DECLARE_LOG_FUNCTION2_EXP(level, arg, expdecl) \
420 extern void expdecl wxVLog##level(arg, const wxChar *szFormat, \
421 va_list argptr); \
422 extern void expdecl wxLog##level(arg, const wxChar *szFormat, \
423 ...) ATTRIBUTE_PRINTF_2
424 #define DECLARE_LOG_FUNCTION2(level, arg) \
425 DECLARE_LOG_FUNCTION2_EXP(level, arg, WXDLLIMPEXP_BASE)
426
427 #else // !wxUSE_LOG
428
429 // log functions do nothing at all
430 #define DECLARE_LOG_FUNCTION(level) \
431 inline void wxVLog##level(const wxChar *szFormat, \
432 va_list argptr) { } \
433 inline void wxLog##level(const wxChar *szFormat, ...) { }
434 #define DECLARE_LOG_FUNCTION2(level, arg) \
435 inline void wxVLog##level(arg, const wxChar *szFormat, \
436 va_list argptr) {} \
437 inline void wxLog##level(arg, const wxChar *szFormat, ...) { }
438
439 // Empty Class to fake wxLogNull
440 class WXDLLIMPEXP_BASE wxLogNull
441 {
442 public:
443 wxLogNull() { }
444 };
445
446 // Dummy macros to replace some functions.
447 #define wxSysErrorCode() (unsigned long)0
448 #define wxSysErrorMsg( X ) (const wxChar*)NULL
449
450 // Fake symbolic trace masks... for those that are used frequently
451 #define wxTRACE_OleCalls wxEmptyString // OLE interface calls
452
453 #endif // wxUSE_LOG/!wxUSE_LOG
454
455 // a generic function for all levels (level is passes as parameter)
456 DECLARE_LOG_FUNCTION2(Generic, wxLogLevel level);
457
458 // one function per each level
459 DECLARE_LOG_FUNCTION(FatalError);
460 DECLARE_LOG_FUNCTION(Error);
461 DECLARE_LOG_FUNCTION(Warning);
462 DECLARE_LOG_FUNCTION(Message);
463 DECLARE_LOG_FUNCTION(Info);
464 DECLARE_LOG_FUNCTION(Verbose);
465
466 // this function sends the log message to the status line of the top level
467 // application frame, if any
468 DECLARE_LOG_FUNCTION(Status);
469
470 #if wxUSE_GUI
471 // this one is the same as previous except that it allows to explicitly
472 // specify the frame to which the output should go
473 DECLARE_LOG_FUNCTION2_EXP(Status, wxFrame *pFrame, WXDLLIMPEXP_CORE);
474 #endif // wxUSE_GUI
475
476 // additional one: as wxLogError, but also logs last system call error code
477 // and the corresponding error message if available
478 DECLARE_LOG_FUNCTION(SysError);
479
480 // and another one which also takes the error code (for those broken APIs
481 // that don't set the errno (like registry APIs in Win32))
482 DECLARE_LOG_FUNCTION2(SysError, long lErrCode);
483
484 // debug functions do nothing in release mode
485 #if wxUSE_LOG_DEBUG
486 DECLARE_LOG_FUNCTION(Debug);
487
488 // first kind of LogTrace is unconditional: it doesn't check the level,
489 DECLARE_LOG_FUNCTION(Trace);
490
491 // this second version will only log the message if the mask had been
492 // added to the list of masks with AddTraceMask()
493 DECLARE_LOG_FUNCTION2(Trace, const wxChar *mask);
494
495 // the last one does nothing if all of level bits are not set
496 // in wxLog::GetActive()->GetTraceMask() - it's deprecated in favour of
497 // string identifiers
498 DECLARE_LOG_FUNCTION2(Trace, wxTraceMask mask);
499 #else //!debug
500 // these functions do nothing in release builds
501 inline void wxVLogDebug(const wxChar *, va_list) { }
502 inline void wxLogDebug(const wxChar *, ...) { }
503 inline void wxVLogTrace(const wxChar *, va_list) { }
504 inline void wxLogTrace(const wxChar *, ...) { }
505 inline void wxVLogTrace(wxTraceMask, const wxChar *, va_list) { }
506 inline void wxLogTrace(wxTraceMask, const wxChar *, ...) { }
507 inline void wxVLogTrace(const wxChar *, const wxChar *, va_list) { }
508 inline void wxLogTrace(const wxChar *, const wxChar *, ...) { }
509 #endif // debug/!debug
510
511 // wxLogFatalError helper: show the (fatal) error to the user in a safe way,
512 // i.e. without using wxMessageBox() for example because it could crash
513 void WXDLLIMPEXP_BASE
514 wxSafeShowMessage(const wxString& title, const wxString& text);
515
516 // ----------------------------------------------------------------------------
517 // debug only logging functions: use them with API name and error code
518 // ----------------------------------------------------------------------------
519
520 #ifdef __WXDEBUG__
521 // make life easier for people using VC++ IDE: clicking on the message
522 // will take us immediately to the place of the failed API
523 #ifdef __VISUALC__
524 #define wxLogApiError(api, rc) \
525 wxLogDebug(wxT("%s(%d): '%s' failed with error 0x%08lx (%s)."), \
526 __TFILE__, __LINE__, api, \
527 (long)rc, wxSysErrorMsg(rc))
528 #else // !VC++
529 #define wxLogApiError(api, rc) \
530 wxLogDebug(wxT("In file %s at line %d: '%s' failed with " \
531 "error 0x%08lx (%s)."), \
532 __TFILE__, __LINE__, api, \
533 (long)rc, wxSysErrorMsg(rc))
534 #endif // VC++/!VC++
535
536 #define wxLogLastError(api) wxLogApiError(api, wxSysErrorCode())
537
538 #else //!debug
539 inline void wxLogApiError(const wxChar *, long) { }
540 inline void wxLogLastError(const wxChar *) { }
541 #endif //debug/!debug
542
543 #endif // _WX_LOG_H_
544