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 /////////////////////////////////////////////////////////////////////////////
17 // ----------------------------------------------------------------------------
18 // common constants for use in wxUSE_LOG/!wxUSE_LOG
19 // ----------------------------------------------------------------------------
21 // the trace masks have been superceded by symbolic trace constants, they're
22 // for compatibility only andwill be removed soon - do NOT use them
24 // meaning of different bits of the trace mask (which allows selectively
25 // enable/disable some trace messages)
26 #define wxTraceMemAlloc 0x0001 // trace memory allocation (new/delete)
27 #define wxTraceMessages 0x0002 // trace window messages/X callbacks
28 #define wxTraceResAlloc 0x0004 // trace GDI resource allocation
29 #define wxTraceRefCount 0x0008 // trace various ref counting operations
32 #define wxTraceOleCalls 0x0100 // OLE interface calls
35 // ----------------------------------------------------------------------------
37 // ----------------------------------------------------------------------------
39 // NB: these types are needed even if wxUSE_LOG == 0
40 typedef unsigned long wxTraceMask
;
41 typedef unsigned long wxLogLevel
;
43 // ----------------------------------------------------------------------------
45 // ----------------------------------------------------------------------------
47 #include "wx/string.h"
51 #include "wx/arrstr.h"
54 #include <time.h> // for time_t
57 #include "wx/dynarray.h"
59 #ifndef wxUSE_LOG_DEBUG
61 # define wxUSE_LOG_DEBUG 1
62 # else // !__WXDEBUG__
63 # define wxUSE_LOG_DEBUG 0
67 // ----------------------------------------------------------------------------
68 // forward declarations
69 // ----------------------------------------------------------------------------
72 class WXDLLIMPEXP_CORE wxTextCtrl
;
73 class WXDLLIMPEXP_CORE wxLogFrame
;
74 class WXDLLIMPEXP_CORE wxFrame
;
75 class WXDLLIMPEXP_CORE wxWindow
;
78 // ----------------------------------------------------------------------------
80 // ----------------------------------------------------------------------------
82 // different standard log levels (you may also define your own)
85 wxLOG_FatalError
, // program can't continue, abort immediately
86 wxLOG_Error
, // a serious error, user must be informed about it
87 wxLOG_Warning
, // user is normally informed about it but may be ignored
88 wxLOG_Message
, // normal message (i.e. normal output of a non GUI app)
89 wxLOG_Status
, // informational: might go to the status line of GUI app
90 wxLOG_Info
, // informational message (a.k.a. 'Verbose')
91 wxLOG_Debug
, // never shown to the user, disabled in release mode
92 wxLOG_Trace
, // trace messages are also only enabled in debug mode
93 wxLOG_Progress
, // used for progress indicator (not yet)
94 wxLOG_User
= 100, // user defined levels start here
98 // symbolic trace masks - wxLogTrace("foo", "some trace message...") will be
99 // discarded unless the string "foo" has been added to the list of allowed
100 // ones with AddTraceMask()
102 #define wxTRACE_MemAlloc wxT("memalloc") // trace memory allocation (new/delete)
103 #define wxTRACE_Messages wxT("messages") // trace window messages/X callbacks
104 #define wxTRACE_ResAlloc wxT("resalloc") // trace GDI resource allocation
105 #define wxTRACE_RefCount wxT("refcount") // trace various ref counting operations
108 #define wxTRACE_OleCalls wxT("ole") // OLE interface calls
111 #include "wx/iosfwrap.h"
113 // ----------------------------------------------------------------------------
114 // derive from this class to redirect (or suppress, or ...) log messages
115 // normally, only a single instance of this class exists but it's not enforced
116 // ----------------------------------------------------------------------------
118 class WXDLLIMPEXP_BASE wxLog
124 // these functions allow to completely disable all log messages
126 // is logging disabled now?
127 static bool IsEnabled() { return ms_doLog
; }
129 // change the flag state, return the previous one
130 static bool EnableLogging(bool doIt
= true)
131 { bool doLogOld
= ms_doLog
; ms_doLog
= doIt
; return doLogOld
; }
133 // static sink function - see DoLog() for function to overload in the
135 static void OnLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
139 // flush shows all messages if they're not logged immediately (FILE
140 // and iostream logs don't need it, but wxGuiLog does to avoid showing
141 // 17 modal dialogs one after another)
142 virtual void Flush();
144 // flush the active target if any
145 static void FlushActive()
147 if ( !ms_suspendCount
)
149 wxLog
*log
= GetActiveTarget();
155 // only one sink is active at each moment
156 // get current log target, will call wxApp::CreateLogTarget() to
157 // create one if none exists
158 static wxLog
*GetActiveTarget();
160 // change log target, pLogger may be NULL
161 static wxLog
*SetActiveTarget(wxLog
*pLogger
);
163 // suspend the message flushing of the main target until the next call
164 // to Resume() - this is mainly for internal use (to prevent wxYield()
165 // from flashing the messages)
166 static void Suspend() { ms_suspendCount
++; }
168 // must be called for each Suspend()!
169 static void Resume() { ms_suspendCount
--; }
171 // functions controlling the default wxLog behaviour
172 // verbose mode is activated by standard command-line '-verbose'
174 static void SetVerbose(bool bVerbose
= true) { ms_bVerbose
= bVerbose
; }
176 // Set log level. Log messages with level > logLevel will not be logged.
177 static void SetLogLevel(wxLogLevel logLevel
) { ms_logLevel
= logLevel
; }
179 // should GetActiveTarget() try to create a new log object if the
181 static void DontCreateOnDemand();
183 // log the count of repeating messages instead of logging the messages
185 static void SetRepetitionCounting(bool bRepetCounting
= true)
186 { ms_bRepetCounting
= bRepetCounting
; }
188 // gets duplicate counting status
189 static bool GetRepetitionCounting() { return ms_bRepetCounting
; }
191 // trace mask (see wxTraceXXX constants for details)
192 static void SetTraceMask(wxTraceMask ulMask
) { ms_ulTraceMask
= ulMask
; }
194 // add string trace mask
195 static void AddTraceMask(const wxString
& str
)
196 { ms_aTraceMasks
.push_back(str
); }
198 // add string trace mask
199 static void RemoveTraceMask(const wxString
& str
);
201 // remove all string trace masks
202 static void ClearTraceMasks();
204 // get string trace masks
205 static const wxArrayString
&GetTraceMasks() { return ms_aTraceMasks
; }
207 // sets the timestamp string: this is used as strftime() format string
208 // for the log targets which add time stamps to the messages - set it
209 // to NULL to disable time stamping completely.
210 static void SetTimestamp(const wxChar
*ts
) { ms_timestamp
= ts
; }
215 // gets the verbose status
216 static bool GetVerbose() { return ms_bVerbose
; }
219 static wxTraceMask
GetTraceMask() { return ms_ulTraceMask
; }
221 // is this trace mask in the list?
222 static bool IsAllowedTraceMask(const wxChar
*mask
);
224 // return the current loglevel limit
225 static wxLogLevel
GetLogLevel() { return ms_logLevel
; }
227 // get the current timestamp format string (may be NULL)
228 static const wxChar
*GetTimestamp() { return ms_timestamp
; }
233 // put the time stamp into the string if ms_timestamp != NULL (don't
234 // change it otherwise)
235 static void TimeStamp(wxString
*str
);
237 // make dtor virtual for all derived classes
241 // this method exists for backwards compatibility only, don't use
242 bool HasPendingMessages() const { return true; }
244 #if WXWIN_COMPATIBILITY_2_6
245 // this function doesn't do anything any more, don't call it
246 wxDEPRECATED( static wxChar
*SetLogBuffer(wxChar
*buf
, size_t size
= 0) );
250 // the logging functions that can be overriden
252 // default DoLog() prepends the time stamp and a prefix corresponding
253 // to the message to szString and then passes it to DoLogString()
254 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
256 // default DoLogString does nothing but is not pure virtual because if
257 // you override DoLog() you might not need it at all
258 virtual void DoLogString(const wxChar
*szString
, time_t t
);
260 // log a line containing the number of times the previous message was
262 // returns: the number
263 static unsigned DoLogNumberOfRepeats();
269 // traditional behaviour or counting repetitions
270 static bool ms_bRepetCounting
;
271 static wxString ms_prevString
; // previous message that was logged
272 // how many times the previous message was logged
273 static unsigned ms_prevCounter
;
274 static time_t ms_prevTimeStamp
;// timestamp of the previous message
275 static wxLogLevel ms_prevLevel
; // level of the previous message
277 static wxLog
*ms_pLogger
; // currently active log sink
278 static bool ms_doLog
; // false => all logging disabled
279 static bool ms_bAutoCreate
; // create new log targets on demand?
280 static bool ms_bVerbose
; // false => ignore LogInfo messages
282 static wxLogLevel ms_logLevel
; // limit logging to levels <= ms_logLevel
284 static size_t ms_suspendCount
; // if positive, logs are not flushed
286 // format string for strftime(), if NULL, time stamping log messages is
288 static const wxChar
*ms_timestamp
;
290 static wxTraceMask ms_ulTraceMask
; // controls wxLogTrace behaviour
291 static wxArrayString ms_aTraceMasks
; // more powerful filter for wxLogTrace
294 // ----------------------------------------------------------------------------
295 // "trivial" derivations of wxLog
296 // ----------------------------------------------------------------------------
298 // log everything to a buffer
299 class WXDLLIMPEXP_BASE wxLogBuffer
: public wxLog
304 // get the string contents with all messages logged
305 const wxString
& GetBuffer() const { return m_str
; }
307 // show the buffer contents to the user in the best possible way (this uses
308 // wxMessageOutputMessageBox) and clear it
309 virtual void Flush();
312 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
313 virtual void DoLogString(const wxChar
*szString
, time_t t
);
318 DECLARE_NO_COPY_CLASS(wxLogBuffer
)
322 // log everything to a "FILE *", stderr by default
323 class WXDLLIMPEXP_BASE wxLogStderr
: public wxLog
326 // redirect log output to a FILE
327 wxLogStderr(FILE *fp
= (FILE *) NULL
);
330 // implement sink function
331 virtual void DoLogString(const wxChar
*szString
, time_t t
);
335 DECLARE_NO_COPY_CLASS(wxLogStderr
)
338 #if wxUSE_STD_IOSTREAM
340 // log everything to an "ostream", cerr by default
341 class WXDLLIMPEXP_BASE wxLogStream
: public wxLog
344 // redirect log output to an ostream
345 wxLogStream(wxSTD ostream
*ostr
= (wxSTD ostream
*) NULL
);
348 // implement sink function
349 virtual void DoLogString(const wxChar
*szString
, time_t t
);
351 // using ptr here to avoid including <iostream.h> from this file
352 wxSTD ostream
*m_ostr
;
355 #endif // wxUSE_STD_IOSTREAM
357 // ----------------------------------------------------------------------------
358 // /dev/null log target: suppress logging until this object goes out of scope
359 // ----------------------------------------------------------------------------
367 // wxFile.Open() normally complains if file can't be opened, we don't
371 if ( !file.Open("bar") )
372 ... process error ourselves ...
374 // ~wxLogNull called, old log sink restored
377 class WXDLLIMPEXP_BASE wxLogNull
380 wxLogNull() : m_flagOld(wxLog::EnableLogging(false)) { }
381 ~wxLogNull() { (void)wxLog::EnableLogging(m_flagOld
); }
384 bool m_flagOld
; // the previous value of the wxLog::ms_doLog
387 // ----------------------------------------------------------------------------
388 // chaining log target: installs itself as a log target and passes all
389 // messages to the real log target given to it in the ctor but also forwards
390 // them to the previously active one
392 // note that you don't have to call SetActiveTarget() with this class, it
393 // does it itself in its ctor
394 // ----------------------------------------------------------------------------
396 class WXDLLIMPEXP_BASE wxLogChain
: public wxLog
399 wxLogChain(wxLog
*logger
);
400 virtual ~wxLogChain();
402 // change the new log target
403 void SetLog(wxLog
*logger
);
405 // this can be used to temporarily disable (and then reenable) passing
406 // messages to the old logger (by default we do pass them)
407 void PassMessages(bool bDoPass
) { m_bPassMessages
= bDoPass
; }
409 // are we passing the messages to the previous log target?
410 bool IsPassingMessages() const { return m_bPassMessages
; }
412 // return the previous log target (may be NULL)
413 wxLog
*GetOldLog() const { return m_logOld
; }
415 // override base class version to flush the old logger as well
416 virtual void Flush();
419 // pass the chain to the old logger if needed
420 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
423 // the current log target
426 // the previous log target
429 // do we pass the messages to the old logger?
430 bool m_bPassMessages
;
432 DECLARE_NO_COPY_CLASS(wxLogChain
)
435 // a chain log target which uses itself as the new logger
436 class WXDLLIMPEXP_BASE wxLogPassThrough
: public wxLogChain
442 DECLARE_NO_COPY_CLASS(wxLogPassThrough
)
446 // include GUI log targets:
447 #include "wx/generic/logg.h"
450 // ============================================================================
452 // ============================================================================
454 // ----------------------------------------------------------------------------
455 // Log functions should be used by application instead of stdio, iostream &c
456 // for log messages for easy redirection
457 // ----------------------------------------------------------------------------
459 // ----------------------------------------------------------------------------
460 // get error code/error message from system in a portable way
461 // ----------------------------------------------------------------------------
463 // return the last system error code
464 WXDLLIMPEXP_BASE
unsigned long wxSysErrorCode();
466 // return the error message for given (or last if 0) error code
467 WXDLLIMPEXP_BASE
const wxChar
* wxSysErrorMsg(unsigned long nErrCode
= 0);
469 // ----------------------------------------------------------------------------
470 // define wxLog<level>
471 // ----------------------------------------------------------------------------
473 #define DECLARE_LOG_FUNCTION(level) \
474 extern void WXDLLIMPEXP_BASE wxVLog##level(const wxChar *szFormat, \
476 extern void WXDLLIMPEXP_BASE wxLog##level(const wxChar *szFormat, \
477 ...) ATTRIBUTE_PRINTF_1
478 #define DECLARE_LOG_FUNCTION2_EXP(level, argclass, arg, expdecl) \
479 extern void expdecl wxVLog##level(argclass arg, \
480 const wxChar *szFormat, \
482 extern void expdecl wxLog##level(argclass arg, \
483 const wxChar *szFormat, \
484 ...) ATTRIBUTE_PRINTF_2
487 // log functions do nothing at all
488 #define DECLARE_LOG_FUNCTION(level) \
489 inline void wxVLog##level(const wxChar *WXUNUSED(szFormat), \
490 va_list WXUNUSED(argptr)) { } \
491 inline void wxLog##level(const wxChar *WXUNUSED(szFormat), \
493 #define DECLARE_LOG_FUNCTION2_EXP(level, argclass, arg, expdecl) \
494 inline void wxVLog##level(argclass WXUNUSED(arg), \
495 const wxChar *WXUNUSED(szFormat), \
496 va_list WXUNUSED(argptr)) {} \
497 inline void wxLog##level(argclass WXUNUSED(arg), \
498 const wxChar *WXUNUSED(szFormat), \
501 // Empty Class to fake wxLogNull
502 class WXDLLIMPEXP_BASE wxLogNull
508 // Dummy macros to replace some functions.
509 #define wxSysErrorCode() (unsigned long)0
510 #define wxSysErrorMsg( X ) (const wxChar*)NULL
512 // Fake symbolic trace masks... for those that are used frequently
513 #define wxTRACE_OleCalls wxEmptyString // OLE interface calls
515 #endif // wxUSE_LOG/!wxUSE_LOG
517 #define DECLARE_LOG_FUNCTION2(level, argclass, arg) \
518 DECLARE_LOG_FUNCTION2_EXP(level, argclass, arg, WXDLLIMPEXP_BASE)
521 // a generic function for all levels (level is passes as parameter)
522 DECLARE_LOG_FUNCTION2(Generic
, wxLogLevel
, level
);
524 // one function per each level
525 DECLARE_LOG_FUNCTION(FatalError
);
526 DECLARE_LOG_FUNCTION(Error
);
527 DECLARE_LOG_FUNCTION(Warning
);
528 DECLARE_LOG_FUNCTION(Message
);
529 DECLARE_LOG_FUNCTION(Info
);
530 DECLARE_LOG_FUNCTION(Verbose
);
532 // this function sends the log message to the status line of the top level
533 // application frame, if any
534 DECLARE_LOG_FUNCTION(Status
);
537 // this one is the same as previous except that it allows to explicitly
538 class WXDLLEXPORT wxFrame
;
539 // specify the frame to which the output should go
540 DECLARE_LOG_FUNCTION2_EXP(Status
, wxFrame
*, pFrame
, WXDLLIMPEXP_CORE
);
543 // additional one: as wxLogError, but also logs last system call error code
544 // and the corresponding error message if available
545 DECLARE_LOG_FUNCTION(SysError
);
547 // and another one which also takes the error code (for those broken APIs
548 // that don't set the errno (like registry APIs in Win32))
549 DECLARE_LOG_FUNCTION2(SysError
, long, lErrCode
);
551 // debug functions do nothing in release mode
552 #if wxUSE_LOG && wxUSE_LOG_DEBUG
553 DECLARE_LOG_FUNCTION(Debug
);
555 // there is no more unconditional LogTrace: it is not different from
556 // LogDebug and it creates overload ambiguities
557 //DECLARE_LOG_FUNCTION(Trace);
559 // this version only logs the message if the mask had been added to the
560 // list of masks with AddTraceMask()
561 DECLARE_LOG_FUNCTION2(Trace
, const wxChar
*, mask
);
563 // and this one does nothing if all of level bits are not set in
564 // wxLog::GetActive()->GetTraceMask() -- it's deprecated in favour of
565 // string identifiers
566 DECLARE_LOG_FUNCTION2(Trace
, wxTraceMask
, mask
);
567 #else //!debug || !wxUSE_LOG
568 // these functions do nothing in release builds, but don't define them as
569 // nothing as it could result in different code structure in debug and
570 // release and this could result in trouble when these macros are used
573 // note that making wxVLogDebug/Trace() themselves (empty inline) functions
574 // is a bad idea as some compilers are stupid enough to not inline even
575 // empty functions if their parameters are complicated enough, but by
576 // defining them as an empty inline function we ensure that even dumbest
577 // compilers optimise them away
578 inline void wxLogNop() { }
580 #define wxVLogDebug(fmt, valist) wxLogNop()
581 #define wxVLogTrace(mask, fmt, valist) wxLogNop()
583 #ifdef HAVE_VARIADIC_MACROS
584 // unlike the inline functions below, this completely removes the
585 // wxLogXXX calls from the object file:
586 #define wxLogDebug(fmt, ...) wxLogNop()
587 #define wxLogTrace(mask, fmt, ...) wxLogNop()
588 #else // !HAVE_VARIADIC_MACROS
589 // note that leaving out "fmt" in the vararg functions provokes a warning
590 // from SGI CC: "the last argument of the varargs function is unnamed"
591 inline void wxLogDebug(const wxChar
*fmt
, ...) { wxUnusedVar(fmt
); }
592 inline void wxLogTrace(wxTraceMask
, const wxChar
*fmt
, ...) { wxUnusedVar(fmt
); }
593 inline void wxLogTrace(const wxChar
*, const wxChar
*fmt
, ...) { wxUnusedVar(fmt
); }
594 #endif // HAVE_VARIADIC_MACROS/!HAVE_VARIADIC_MACROS
595 #endif // debug/!debug
597 // wxLogFatalError helper: show the (fatal) error to the user in a safe way,
598 // i.e. without using wxMessageBox() for example because it could crash
599 void WXDLLIMPEXP_BASE
600 wxSafeShowMessage(const wxString
& title
, const wxString
& text
);
602 // ----------------------------------------------------------------------------
603 // debug only logging functions: use them with API name and error code
604 // ----------------------------------------------------------------------------
607 // make life easier for people using VC++ IDE: clicking on the message
608 // will take us immediately to the place of the failed API
610 #define wxLogApiError(api, rc) \
611 wxLogDebug(wxT("%s(%d): '%s' failed with error 0x%08lx (%s)."), \
612 __TFILE__, __LINE__, api, \
613 (long)rc, wxSysErrorMsg(rc))
615 #define wxLogApiError(api, rc) \
616 wxLogDebug(wxT("In file %s at line %d: '%s' failed with ") \
617 wxT("error 0x%08lx (%s)."), \
618 __TFILE__, __LINE__, api, \
619 (long)rc, wxSysErrorMsg(rc))
622 #define wxLogLastError(api) wxLogApiError(api, wxSysErrorCode())
625 #define wxLogApiError(api, err) wxLogNop()
626 #define wxLogLastError(api) wxLogNop()
627 #endif //debug/!debug
629 // wxCocoa has additiional trace masks
630 #if defined(__WXCOCOA__)
631 #include "wx/cocoa/log.h"