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