1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Assorted wxLogXXX functions, and wxLog (sink for logs)
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
15 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
16 #pragma interface "log.h"
21 // ----------------------------------------------------------------------------
22 // common constants for use in wxUSE_LOG/!wxUSE_LOG
23 // ----------------------------------------------------------------------------
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
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
36 #define wxTraceOleCalls 0x0100 // OLE interface calls
39 // ----------------------------------------------------------------------------
41 // ----------------------------------------------------------------------------
43 // NB: these types are needed even if wxUSE_LOG == 0
44 typedef unsigned long wxTraceMask
;
45 typedef unsigned long wxLogLevel
;
47 // ----------------------------------------------------------------------------
49 // ----------------------------------------------------------------------------
51 #include "wx/string.h"
55 #include "wx/arrstr.h"
58 #include <time.h> // for time_t
61 #include "wx/dynarray.h"
63 #ifndef wxUSE_LOG_DEBUG
65 # define wxUSE_LOG_DEBUG 1
66 # else // !__WXDEBUG__
67 # define wxUSE_LOG_DEBUG 0
71 // ----------------------------------------------------------------------------
72 // forward declarations
73 // ----------------------------------------------------------------------------
76 class WXDLLIMPEXP_CORE wxTextCtrl
;
77 class WXDLLIMPEXP_CORE wxLogFrame
;
78 class WXDLLIMPEXP_CORE wxFrame
;
79 class WXDLLIMPEXP_CORE wxWindow
;
82 // ----------------------------------------------------------------------------
84 // ----------------------------------------------------------------------------
86 // different standard log levels (you may also define your own)
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
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()
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
112 #define wxTRACE_OleCalls wxT("ole") // OLE interface calls
115 #include "wx/iosfwrap.h"
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 // ----------------------------------------------------------------------------
122 class WXDLLIMPEXP_BASE wxLog
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 );
135 // these functions allow to completely disable all log messages
137 // is logging disabled now?
138 static bool IsEnabled() { return ms_doLog
; }
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
; }
144 // static sink function - see DoLog() for function to overload in the
146 static void OnLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
148 if ( IsEnabled() && ms_logLevel
>= level
)
150 wxLog
*pLogger
= GetActiveTarget();
152 pLogger
->DoLog(level
, szString
, t
);
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();
163 // flush the active target if any
164 static void FlushActive()
166 if ( !ms_suspendCount
)
168 wxLog
*log
= GetActiveTarget();
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();
179 // change log target, pLogger may be NULL
180 static wxLog
*SetActiveTarget(wxLog
*pLogger
);
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
++; }
187 // must be called for each Suspend()!
188 static void Resume() { ms_suspendCount
--; }
190 // functions controlling the default wxLog behaviour
191 // verbose mode is activated by standard command-line '-verbose'
193 static void SetVerbose(bool bVerbose
= true) { ms_bVerbose
= bVerbose
; }
195 // Set log level. Log messages with level > logLevel will not be logged.
196 static void SetLogLevel(wxLogLevel logLevel
) { ms_logLevel
= logLevel
; }
198 // should GetActiveTarget() try to create a new log object if the
200 static void DontCreateOnDemand();
202 // trace mask (see wxTraceXXX constants for details)
203 static void SetTraceMask(wxTraceMask ulMask
) { ms_ulTraceMask
= ulMask
; }
205 // add string trace mask
206 static void AddTraceMask(const wxString
& str
)
207 { ms_aTraceMasks
.push_back(str
); }
209 // add string trace mask
210 static void RemoveTraceMask(const wxString
& str
);
212 // remove all string trace masks
213 static void ClearTraceMasks();
215 // get string trace masks
216 static const wxArrayString
&GetTraceMasks() { return ms_aTraceMasks
; }
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
; }
226 // gets the verbose status
227 static bool GetVerbose() { return ms_bVerbose
; }
230 static wxTraceMask
GetTraceMask() { return ms_ulTraceMask
; }
232 // is this trace mask in the list?
233 static bool IsAllowedTraceMask(const wxChar
*mask
);
235 // return the current loglevel limit
236 static wxLogLevel
GetLogLevel() { return ms_logLevel
; }
238 // get the current timestamp format string (may be NULL)
239 static const wxChar
*GetTimestamp() { return ms_timestamp
; }
244 // put the time stamp into the string if ms_timestamp != NULL (don't
245 // change it otherwise)
246 static void TimeStamp(wxString
*str
);
248 // make dtor virtual for all derived classes
252 // this method exists for backwards compatibility only, don't use
253 bool HasPendingMessages() const { return true; }
256 // the logging functions that can be overriden
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
);
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
);
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
275 static wxLogLevel ms_logLevel
; // limit logging to levels <= ms_logLevel
277 static size_t ms_suspendCount
; // if positive, logs are not flushed
279 // format string for strftime(), if NULL, time stamping log messages is
281 static const wxChar
*ms_timestamp
;
283 static wxTraceMask ms_ulTraceMask
; // controls wxLogTrace behaviour
284 static wxArrayString ms_aTraceMasks
; // more powerful filter for wxLogTrace
287 // ----------------------------------------------------------------------------
288 // "trivial" derivations of wxLog
289 // ----------------------------------------------------------------------------
291 #if wxABI_VERSION > 20601
293 // log everything to a buffer
294 class WXDLLIMPEXP_BASE wxLogBuffer
: public wxLog
299 // get the string contents with all messages logged
300 const wxString
& GetBuffer() const { return m_str
; }
302 // show the buffer contents to the user in the best possible way (this uses
303 // wxMessageOutputMessageBox) and clear it
304 virtual void Flush();
307 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
308 virtual void DoLogString(const wxChar
*szString
, time_t t
);
313 DECLARE_NO_COPY_CLASS(wxLogBuffer
)
316 #endif // wxABI_VERSION
318 // log everything to a "FILE *", stderr by default
319 class WXDLLIMPEXP_BASE wxLogStderr
: public wxLog
322 // redirect log output to a FILE
323 wxLogStderr(FILE *fp
= (FILE *) NULL
);
326 // implement sink function
327 virtual void DoLogString(const wxChar
*szString
, time_t t
);
331 DECLARE_NO_COPY_CLASS(wxLogStderr
)
334 #if wxUSE_STD_IOSTREAM
336 // log everything to an "ostream", cerr by default
337 class WXDLLIMPEXP_BASE wxLogStream
: public wxLog
340 // redirect log output to an ostream
341 wxLogStream(wxSTD ostream
*ostr
= (wxSTD ostream
*) NULL
);
344 // implement sink function
345 virtual void DoLogString(const wxChar
*szString
, time_t t
);
347 // using ptr here to avoid including <iostream.h> from this file
348 wxSTD ostream
*m_ostr
;
351 #endif // wxUSE_STD_IOSTREAM
353 // ----------------------------------------------------------------------------
354 // /dev/null log target: suppress logging until this object goes out of scope
355 // ----------------------------------------------------------------------------
363 // wxFile.Open() normally complains if file can't be opened, we don't
367 if ( !file.Open("bar") )
368 ... process error ourselves ...
370 // ~wxLogNull called, old log sink restored
373 class WXDLLIMPEXP_BASE wxLogNull
376 wxLogNull() : m_flagOld(wxLog::EnableLogging(false)) { }
377 ~wxLogNull() { (void)wxLog::EnableLogging(m_flagOld
); }
380 bool m_flagOld
; // the previous value of the wxLog::ms_doLog
383 // ----------------------------------------------------------------------------
384 // chaining log target: installs itself as a log target and passes all
385 // messages to the real log target given to it in the ctor but also forwards
386 // them to the previously active one
388 // note that you don't have to call SetActiveTarget() with this class, it
389 // does it itself in its ctor
390 // ----------------------------------------------------------------------------
392 class WXDLLIMPEXP_BASE wxLogChain
: public wxLog
395 wxLogChain(wxLog
*logger
);
396 virtual ~wxLogChain();
398 // change the new log target
399 void SetLog(wxLog
*logger
);
401 // this can be used to temporarily disable (and then reenable) passing
402 // messages to the old logger (by default we do pass them)
403 void PassMessages(bool bDoPass
) { m_bPassMessages
= bDoPass
; }
405 // are we passing the messages to the previous log target?
406 bool IsPassingMessages() const { return m_bPassMessages
; }
408 // return the previous log target (may be NULL)
409 wxLog
*GetOldLog() const { return m_logOld
; }
411 // override base class version to flush the old logger as well
412 virtual void Flush();
415 // pass the chain to the old logger if needed
416 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
419 // the current log target
422 // the previous log target
425 // do we pass the messages to the old logger?
426 bool m_bPassMessages
;
428 DECLARE_NO_COPY_CLASS(wxLogChain
)
431 // a chain log target which uses itself as the new logger
432 class WXDLLIMPEXP_BASE wxLogPassThrough
: public wxLogChain
438 DECLARE_NO_COPY_CLASS(wxLogPassThrough
)
442 // include GUI log targets:
443 #include "wx/generic/logg.h"
446 // ============================================================================
448 // ============================================================================
450 // ----------------------------------------------------------------------------
451 // Log functions should be used by application instead of stdio, iostream &c
452 // for log messages for easy redirection
453 // ----------------------------------------------------------------------------
455 // ----------------------------------------------------------------------------
456 // get error code/error message from system in a portable way
457 // ----------------------------------------------------------------------------
459 // return the last system error code
460 WXDLLIMPEXP_BASE
unsigned long wxSysErrorCode();
462 // return the error message for given (or last if 0) error code
463 WXDLLIMPEXP_BASE
const wxChar
* wxSysErrorMsg(unsigned long nErrCode
= 0);
465 // ----------------------------------------------------------------------------
466 // define wxLog<level>
467 // ----------------------------------------------------------------------------
469 #define DECLARE_LOG_FUNCTION(level) \
470 extern void WXDLLIMPEXP_BASE wxVLog##level(const wxChar *szFormat, \
472 extern void WXDLLIMPEXP_BASE wxLog##level(const wxChar *szFormat, \
473 ...) ATTRIBUTE_PRINTF_1
474 #define DECLARE_LOG_FUNCTION2_EXP(level, argclass, arg, expdecl) \
475 extern void expdecl wxVLog##level(argclass arg, \
476 const wxChar *szFormat, \
478 extern void expdecl wxLog##level(argclass arg, \
479 const wxChar *szFormat, \
480 ...) ATTRIBUTE_PRINTF_2
483 // log functions do nothing at all
484 #define DECLARE_LOG_FUNCTION(level) \
485 inline void wxVLog##level(const wxChar *WXUNUSED(szFormat), \
486 va_list WXUNUSED(argptr)) { } \
487 inline void wxLog##level(const wxChar *WXUNUSED(szFormat), \
489 #define DECLARE_LOG_FUNCTION2_EXP(level, argclass, arg, expdecl) \
490 inline void wxVLog##level(argclass WXUNUSED(arg), \
491 const wxChar *WXUNUSED(szFormat), \
492 va_list WXUNUSED(argptr)) {} \
493 inline void wxLog##level(argclass WXUNUSED(arg), \
494 const wxChar *WXUNUSED(szFormat), \
497 // Empty Class to fake wxLogNull
498 class WXDLLIMPEXP_BASE wxLogNull
504 // Dummy macros to replace some functions.
505 #define wxSysErrorCode() (unsigned long)0
506 #define wxSysErrorMsg( X ) (const wxChar*)NULL
508 // Fake symbolic trace masks... for those that are used frequently
509 #define wxTRACE_OleCalls wxEmptyString // OLE interface calls
511 #endif // wxUSE_LOG/!wxUSE_LOG
512 #define DECLARE_LOG_FUNCTION2(level, argclass, arg) \
513 DECLARE_LOG_FUNCTION2_EXP(level, argclass, arg, WXDLLIMPEXP_BASE)
516 // a generic function for all levels (level is passes as parameter)
517 DECLARE_LOG_FUNCTION2(Generic
, wxLogLevel
, level
);
519 // one function per each level
520 DECLARE_LOG_FUNCTION(FatalError
);
521 DECLARE_LOG_FUNCTION(Error
);
522 DECLARE_LOG_FUNCTION(Warning
);
523 DECLARE_LOG_FUNCTION(Message
);
524 DECLARE_LOG_FUNCTION(Info
);
525 DECLARE_LOG_FUNCTION(Verbose
);
527 // this function sends the log message to the status line of the top level
528 // application frame, if any
529 DECLARE_LOG_FUNCTION(Status
);
532 // this one is the same as previous except that it allows to explicitly
533 class WXDLLEXPORT wxFrame
;
534 // specify the frame to which the output should go
535 DECLARE_LOG_FUNCTION2_EXP(Status
, wxFrame
*, pFrame
, WXDLLIMPEXP_CORE
);
538 // additional one: as wxLogError, but also logs last system call error code
539 // and the corresponding error message if available
540 DECLARE_LOG_FUNCTION(SysError
);
542 // and another one which also takes the error code (for those broken APIs
543 // that don't set the errno (like registry APIs in Win32))
544 DECLARE_LOG_FUNCTION2(SysError
, long, lErrCode
);
546 // debug functions do nothing in release mode
548 DECLARE_LOG_FUNCTION(Debug
);
550 // there is no more unconditional LogTrace: it is not different from
551 // LogDebug and it creates overload ambiguities
552 //DECLARE_LOG_FUNCTION(Trace);
554 // this version only logs the message if the mask had been added to the
555 // list of masks with AddTraceMask()
556 DECLARE_LOG_FUNCTION2(Trace
, const wxChar
*, mask
);
558 // and this one does nothing if all of level bits are not set in
559 // wxLog::GetActive()->GetTraceMask() -- it's deprecated in favour of
560 // string identifiers
561 DECLARE_LOG_FUNCTION2(Trace
, wxTraceMask
, mask
);
563 // these functions do nothing in release builds
565 // note that leaving out "fmt" in the vararg functions provokes a warning
566 // from SGI CC: "the last argument of the varargs function is unnamed"
567 inline void wxVLogDebug(const wxChar
*, va_list) { }
568 inline void wxLogDebug(const wxChar
*fmt
, ...) { wxUnusedVar(fmt
); }
569 inline void wxVLogTrace(wxTraceMask
, const wxChar
*, va_list) { }
570 inline void wxLogTrace(wxTraceMask
, const wxChar
*fmt
, ...) { wxUnusedVar(fmt
); }
571 inline void wxVLogTrace(const wxChar
*, const wxChar
*, va_list) { }
572 inline void wxLogTrace(const wxChar
*, const wxChar
*fmt
, ...) { wxUnusedVar(fmt
); }
573 #endif // debug/!debug
575 // wxLogFatalError helper: show the (fatal) error to the user in a safe way,
576 // i.e. without using wxMessageBox() for example because it could crash
577 void WXDLLIMPEXP_BASE
578 wxSafeShowMessage(const wxString
& title
, const wxString
& text
);
580 // ----------------------------------------------------------------------------
581 // debug only logging functions: use them with API name and error code
582 // ----------------------------------------------------------------------------
585 // make life easier for people using VC++ IDE: clicking on the message
586 // will take us immediately to the place of the failed API
588 #define wxLogApiError(api, rc) \
589 wxLogDebug(wxT("%s(%d): '%s' failed with error 0x%08lx (%s)."), \
590 __TFILE__, __LINE__, api, \
591 (long)rc, wxSysErrorMsg(rc))
593 #define wxLogApiError(api, rc) \
594 wxLogDebug(wxT("In file %s at line %d: '%s' failed with ") \
595 wxT("error 0x%08lx (%s)."), \
596 __TFILE__, __LINE__, api, \
597 (long)rc, wxSysErrorMsg(rc))
600 #define wxLogLastError(api) wxLogApiError(api, wxSysErrorCode())
603 inline void wxLogApiError(const wxChar
*, long) { }
604 inline void wxLogLastError(const wxChar
*) { }
605 #endif //debug/!debug
607 // wxCocoa has additiional trace masks
608 #if defined(__WXCOCOA__)
609 #include "wx/cocoa/log.h"