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