]> git.saurik.com Git - wxWidgets.git/blob - include/wx/log.h
Trying to hide evidence of my negative programming skills...
[wxWidgets.git] / include / wx / log.h
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: 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 // these functions allow to completely disable all log messages
107 // is logging disabled now?
108 static bool IsEnabled() { return ms_doLog; }
109 // change the flag state, return the previous one
110 static bool EnableLogging(bool doIt = TRUE)
111 { bool doLogOld = ms_doLog; ms_doLog = doIt; return doLogOld; }
112
113 // static sink function - see DoLog() for function to overload in the
114 // derived classes
115 static void OnLog(wxLogLevel level, const wxChar *szString, time_t t)
116 {
117 if ( IsEnabled() ) {
118 wxLog *pLogger = GetActiveTarget();
119 if ( pLogger )
120 pLogger->DoLog(level, szString, t);
121 }
122 }
123
124 // message buffering
125 // flush shows all messages if they're not logged immediately (FILE
126 // and iostream logs don't need it, but wxGuiLog does to avoid showing
127 // 17 modal dialogs one after another)
128 virtual void Flush();
129 // call to Flush() may be optimized: call it only if this function
130 // returns true (although Flush() also returns immediately if there is
131 // no messages, this functions is more efficient because inline)
132 bool HasPendingMessages() const { return m_bHasMessages; }
133
134 // only one sink is active at each moment
135 // flush the active target if any
136 static void FlushActive()
137 {
138 if ( !ms_suspendCount )
139 {
140 wxLog *log = GetActiveTarget();
141 if ( log && log->HasPendingMessages() )
142 log->Flush();
143 }
144 }
145 // get current log target, will call wxApp::CreateLogTarget() to
146 // create one if none exists
147 static wxLog *GetActiveTarget();
148 // change log target, pLogger may be NULL
149 static wxLog *SetActiveTarget(wxLog *pLogger);
150
151 // suspend the message flushing of the main target until the next call
152 // to Resume() - this is mainly for internal use (to prevent wxYield()
153 // from flashing the messages)
154 static void Suspend() { ms_suspendCount++; }
155 // must be called for each Suspend()!
156 static void Resume() { ms_suspendCount--; }
157
158 // functions controlling the default wxLog behaviour
159 // verbose mode is activated by standard command-line '-verbose'
160 // option
161 void SetVerbose(bool bVerbose = TRUE) { m_bVerbose = bVerbose; }
162 // should GetActiveTarget() try to create a new log object if the
163 // current is NULL?
164 static void DontCreateOnDemand();
165
166 // trace mask (see wxTraceXXX constants for details)
167 static void SetTraceMask(wxTraceMask ulMask) { ms_ulTraceMask = ulMask; }
168 // add string trace mask
169 static void AddTraceMask(const wxString& str) { ms_aTraceMasks.Add(str); }
170 // add string trace mask
171 static void RemoveTraceMask(const wxString& str);
172 // remove all string trace masks
173 static void ClearTraceMasks();
174
175 // sets the timestamp string: this is used as strftime() format string
176 // for the log targets which add time stamps to the messages - set it
177 // to NULL to disable time stamping completely.
178 static void SetTimestamp(const wxChar *ts) { ms_timestamp = ts; }
179
180 // accessors
181 // gets the verbose status
182 bool GetVerbose() const { return m_bVerbose; }
183 // get trace mask
184 static wxTraceMask GetTraceMask() { return ms_ulTraceMask; }
185 // is this trace mask in the list?
186 static bool IsAllowedTraceMask(const wxChar *mask)
187 { return ms_aTraceMasks.Index(mask) != wxNOT_FOUND; }
188
189 // get the current timestamp format string (may be NULL)
190 static const wxChar *GetTimestamp() { return ms_timestamp; }
191
192 // helpers
193 // put the time stamp into the string if ms_timestamp != NULL (don't
194 // change it otherwise)
195 static void TimeStamp(wxString *str);
196
197 // make dtor virtual for all derived classes
198 virtual ~wxLog() { }
199
200 protected:
201 bool m_bHasMessages; // any messages in the queue?
202 bool m_bVerbose; // FALSE => ignore LogInfo messages
203
204 // the logging functions that can be overriden
205 // default DoLog() prepends the time stamp and a prefix corresponding
206 // to the message to szString and then passes it to DoLogString()
207 virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t);
208 // default DoLogString does nothing but is not pure virtual because if
209 // you override DoLog() you might not need it at all
210 virtual void DoLogString(const wxChar *szString, time_t t);
211
212 private:
213 // static variables
214 // ----------------
215
216 static wxLog *ms_pLogger; // currently active log sink
217 static bool ms_doLog; // FALSE => all logging disabled
218 static bool ms_bAutoCreate; // create new log targets on demand?
219
220 static size_t ms_suspendCount; // if positive, logs are not flushed
221
222 // format string for strftime(), if NULL, time stamping log messages is
223 // disabled
224 static const wxChar *ms_timestamp;
225
226 static wxTraceMask ms_ulTraceMask; // controls wxLogTrace behaviour
227 static wxArrayString ms_aTraceMasks; // more powerful filter for wxLogTrace
228 };
229
230 // ----------------------------------------------------------------------------
231 // "trivial" derivations of wxLog
232 // ----------------------------------------------------------------------------
233
234 // log everything to a "FILE *", stderr by default
235 class WXDLLEXPORT wxLogStderr : public wxLog
236 {
237 public:
238 // redirect log output to a FILE
239 wxLogStderr(FILE *fp = (FILE *) NULL);
240
241 private:
242 // implement sink function
243 virtual void DoLogString(const wxChar *szString, time_t t);
244
245 FILE *m_fp;
246 };
247
248 #if wxUSE_STD_IOSTREAM
249 // log everything to an "ostream", cerr by default
250 class WXDLLEXPORT wxLogStream : public wxLog
251 {
252 public:
253 // redirect log output to an ostream
254 wxLogStream(wxSTD ostream *ostr = (wxSTD ostream *) NULL);
255
256 protected:
257 // implement sink function
258 virtual void DoLogString(const wxChar *szString, time_t t);
259
260 // using ptr here to avoid including <iostream.h> from this file
261 wxSTD ostream *m_ostr;
262 };
263 #endif
264
265 // the following log targets are only compiled in if the we're compiling the
266 // GUI part (andnot just the base one) of the library, they're implemented in
267 // src/generic/logg.cpp *and not src/common/log.cpp unlike all the rest)
268
269 #if wxUSE_GUI
270
271 #if wxUSE_TEXTCTRL
272
273 // log everything to a text window (GUI only of course)
274 class WXDLLEXPORT wxLogTextCtrl : public wxLog
275 {
276 public:
277 wxLogTextCtrl(wxTextCtrl *pTextCtrl);
278
279 private:
280 // implement sink function
281 virtual void DoLogString(const wxChar *szString, time_t t);
282
283 // the control we use
284 wxTextCtrl *m_pTextCtrl;
285 };
286
287 #endif // wxUSE_TEXTCTRL
288
289 // ----------------------------------------------------------------------------
290 // GUI log target, the default one for wxWindows programs
291 // ----------------------------------------------------------------------------
292
293 #if wxUSE_LOGGUI
294
295 class WXDLLEXPORT wxLogGui : public wxLog
296 {
297 public:
298 // ctor
299 wxLogGui();
300
301 // show all messages that were logged since the last Flush()
302 virtual void Flush();
303
304 protected:
305 virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t);
306
307 // empty everything
308 void Clear();
309
310 wxArrayString m_aMessages; // the log message texts
311 wxArrayInt m_aSeverity; // one of wxLOG_XXX values
312 wxArrayLong m_aTimes; // the time of each message
313 bool m_bErrors, // do we have any errors?
314 m_bWarnings; // any warnings?
315 };
316
317 #endif // wxUSE_LOGGUI
318
319 // ----------------------------------------------------------------------------
320 // (background) log window: this class forwards all log messages to the log
321 // target which was active when it was instantiated, but also collects them
322 // to the log window. This window has it's own menu which allows the user to
323 // close it, clear the log contents or save it to the file.
324 // ----------------------------------------------------------------------------
325
326 #if wxUSE_LOGWINDOW
327
328 class WXDLLEXPORT wxLogWindow : public wxLog
329 {
330 public:
331 wxLogWindow(wxFrame *pParent, // the parent frame (can be NULL)
332 const wxChar *szTitle, // the title of the frame
333 bool bShow = TRUE, // show window immediately?
334 bool bPassToOld = TRUE); // pass log messages to the old target?
335 ~wxLogWindow();
336
337 // window operations
338 // show/hide the log window
339 void Show(bool bShow = TRUE);
340 // retrieve the pointer to the frame
341 wxFrame *GetFrame() const;
342
343 // accessors
344 // the previous log target (may be NULL)
345 wxLog *GetOldLog() const { return m_pOldLog; }
346 // are we passing the messages to the previous log target?
347 bool IsPassingMessages() const { return m_bPassMessages; }
348
349 // we can pass the messages to the previous log target (we're in this mode by
350 // default: we collect all messages in the window, but also let the default
351 // processing take place)
352 void PassMessages(bool bDoPass) { m_bPassMessages = bDoPass; }
353
354 // base class virtuals
355 // we don't need it ourselves, but we pass it to the previous logger
356 virtual void Flush();
357
358 // overridables
359 // called immediately after the log frame creation allowing for
360 // any extra initializations
361 virtual void OnFrameCreate(wxFrame *frame);
362 // called if the user closes the window interactively, will not be
363 // called if it is destroyed for another reason (such as when program
364 // exits) - return TRUE from here to allow the frame to close, FALSE
365 // to prevent this from happening
366 virtual bool OnFrameClose(wxFrame *frame);
367 // called right before the log frame is going to be deleted: will
368 // always be called unlike OnFrameClose()
369 virtual void OnFrameDelete(wxFrame *frame);
370
371 protected:
372 virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t);
373 virtual void DoLogString(const wxChar *szString, time_t t);
374
375 private:
376 bool m_bPassMessages; // pass messages to m_pOldLog?
377 wxLog *m_pOldLog; // previous log target
378 wxLogFrame *m_pLogFrame; // the log frame
379 };
380
381 #endif // wxUSE_LOGWINDOW
382
383 #endif // wxUSE_GUI
384
385 // ----------------------------------------------------------------------------
386 // /dev/null log target: suppress logging until this object goes out of scope
387 // ----------------------------------------------------------------------------
388
389 // example of usage:
390 /*
391 void Foo() {
392 wxFile file;
393
394 // wxFile.Open() normally complains if file can't be opened, we don't want it
395 wxLogNull logNo;
396 if ( !file.Open("bar") )
397 ... process error ourselves ...
398
399 // ~wxLogNull called, old log sink restored
400 }
401 */
402 class WXDLLEXPORT wxLogNull
403 {
404 public:
405 wxLogNull() { m_flagOld = wxLog::EnableLogging(FALSE); }
406 ~wxLogNull() { (void)wxLog::EnableLogging(m_flagOld); }
407
408 private:
409 bool m_flagOld; // the previous value of the wxLog::ms_doLog
410 };
411
412 // ============================================================================
413 // global functions
414 // ============================================================================
415
416 // ----------------------------------------------------------------------------
417 // Log functions should be used by application instead of stdio, iostream &c
418 // for log messages for easy redirection
419 // ----------------------------------------------------------------------------
420
421 // are we in 'verbose' mode?
422 // (note that it's often handy to change this var manually from the
423 // debugger, thus enabling/disabling verbose reporting for some
424 // parts of the program only)
425 WXDLLEXPORT_DATA(extern bool) g_bVerbose;
426
427 // ----------------------------------------------------------------------------
428 // get error code/error message from system in a portable way
429 // ----------------------------------------------------------------------------
430
431 // return the last system error code
432 WXDLLEXPORT unsigned long wxSysErrorCode();
433 // return the error message for given (or last if 0) error code
434 WXDLLEXPORT const wxChar* wxSysErrorMsg(unsigned long nErrCode = 0);
435
436 // define wxLog<level>
437 // -------------------
438
439 #define DECLARE_LOG_FUNCTION(level) \
440 extern void WXDLLEXPORT wxLog##level(const wxChar *szFormat, ...)
441 #define DECLARE_LOG_FUNCTION2(level, arg1) \
442 extern void WXDLLEXPORT wxLog##level(arg1, const wxChar *szFormat, ...)
443
444 #else // !wxUSE_LOG
445
446 // log functions do nothing at all
447 #define DECLARE_LOG_FUNCTION(level) \
448 inline void WXDLLEXPORT wxLog##level(const wxChar *szFormat, ...) {}
449 #define DECLARE_LOG_FUNCTION2(level, arg1) \
450 inline void WXDLLEXPORT wxLog##level(arg1, const wxChar *szFormat, ...) {}
451
452 #endif // wxUSE_LOG/!wxUSE_LOG
453
454 // a generic function for all levels (level is passes as parameter)
455 DECLARE_LOG_FUNCTION2(Generic, wxLogLevel level);
456
457 // one function per each level
458 DECLARE_LOG_FUNCTION(FatalError);
459 DECLARE_LOG_FUNCTION(Error);
460 DECLARE_LOG_FUNCTION(Warning);
461 DECLARE_LOG_FUNCTION(Message);
462 DECLARE_LOG_FUNCTION(Info);
463 DECLARE_LOG_FUNCTION(Verbose);
464
465 // this function sends the log message to the status line of the top level
466 // application frame, if any
467 DECLARE_LOG_FUNCTION(Status);
468
469 // this one is the same as previous except that it allows to explicitly
470 // specify the frame to which the output should go
471 DECLARE_LOG_FUNCTION2(Status, wxFrame *pFrame);
472
473 // additional one: as wxLogError, but also logs last system call error code
474 // and the corresponding error message if available
475 DECLARE_LOG_FUNCTION(SysError);
476
477 // and another one which also takes the error code (for those broken APIs
478 // that don't set the errno (like registry APIs in Win32))
479 DECLARE_LOG_FUNCTION2(SysError, long lErrCode);
480
481 // debug functions do nothing in release mode
482 #ifdef __WXDEBUG__
483 DECLARE_LOG_FUNCTION(Debug);
484
485 // first king of LogTrace is uncoditional: it doesn't check the level,
486 DECLARE_LOG_FUNCTION(Trace);
487
488 // this second version will only log the message if the mask had been
489 // added to the list of masks with AddTraceMask()
490 DECLARE_LOG_FUNCTION2(Trace, const wxChar *mask);
491
492 // the last one does nothing if all of level bits are not set
493 // in wxLog::GetActive()->GetTraceMask() - it's deprecated in favour of
494 // string identifiers
495 DECLARE_LOG_FUNCTION2(Trace, wxTraceMask mask);
496 #else //!debug
497 // these functions do nothing in release builds
498 inline void wxLogDebug(const wxChar *, ...) { }
499 inline void wxLogTrace(const wxChar *, ...) { }
500 inline void wxLogTrace(wxTraceMask, const wxChar *, ...) { }
501 inline void wxLogTrace(const wxChar *, const wxChar *, ...) { }
502 #endif // debug/!debug
503
504 // ----------------------------------------------------------------------------
505 // debug only logging functions: use them with API name and error code
506 // ----------------------------------------------------------------------------
507
508 #ifndef __TFILE__
509 #define __XFILE__(x) Tx)
510 #define __TFILE__ __XFILE__(__FILE__)
511 #endif
512
513 #ifdef __WXDEBUG__
514 // make life easier for people using VC++ IDE: clicking on the message
515 // will take us immediately to the place of the failed API
516 #ifdef __VISUALC__
517 #define wxLogApiError(api, rc) \
518 wxLogDebug(wxT("%s(%d): '%s' failed with error 0x%08lx (%s)."), \
519 __TFILE__, __LINE__, api, \
520 rc, wxSysErrorMsg(rc))
521 #else // !VC++
522 #define wxLogApiError(api, rc) \
523 wxLogDebug(wxT("In file %s at line %d: '%s' failed with " \
524 "error 0x%08lx (%s)."), \
525 __TFILE__, __LINE__, api, \
526 rc, wxSysErrorMsg(rc))
527 #endif // VC++/!VC++
528
529 #define wxLogLastError(api) wxLogApiError(api, wxSysErrorCode())
530
531 #else //!debug
532 inline void wxLogApiError(const wxChar *, long) { }
533 inline void wxLogLastError(const wxChar *) { }
534 #endif //debug/!debug
535
536 #endif // _WX_LOG_H_