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