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
126 // Allow replacement of the fixed size static buffer with
127 // a user allocated one. Pass in NULL to restore the
128 // built in static buffer.
129 static wxChar
*SetLogBuffer( wxChar
*buf
, size_t size
= 0 );
131 // these functions allow to completely disable all log messages
133 // is logging disabled now?
134 static bool IsEnabled() { return ms_doLog
; }
136 // change the flag state, return the previous one
137 static bool EnableLogging(bool doIt
= true)
138 { bool doLogOld
= ms_doLog
; ms_doLog
= doIt
; return doLogOld
; }
140 // static sink function - see DoLog() for function to overload in the
142 static void OnLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
146 // flush shows all messages if they're not logged immediately (FILE
147 // and iostream logs don't need it, but wxGuiLog does to avoid showing
148 // 17 modal dialogs one after another)
149 virtual void Flush();
151 // flush the active target if any
152 static void FlushActive()
154 if ( !ms_suspendCount
)
156 wxLog
*log
= GetActiveTarget();
162 // only one sink is active at each moment
163 // get current log target, will call wxApp::CreateLogTarget() to
164 // create one if none exists
165 static wxLog
*GetActiveTarget();
167 // change log target, pLogger may be NULL
168 static wxLog
*SetActiveTarget(wxLog
*pLogger
);
170 // suspend the message flushing of the main target until the next call
171 // to Resume() - this is mainly for internal use (to prevent wxYield()
172 // from flashing the messages)
173 static void Suspend() { ms_suspendCount
++; }
175 // must be called for each Suspend()!
176 static void Resume() { ms_suspendCount
--; }
178 // functions controlling the default wxLog behaviour
179 // verbose mode is activated by standard command-line '-verbose'
181 static void SetVerbose(bool bVerbose
= true) { ms_bVerbose
= bVerbose
; }
183 // Set log level. Log messages with level > logLevel will not be logged.
184 static void SetLogLevel(wxLogLevel logLevel
) { ms_logLevel
= logLevel
; }
186 // should GetActiveTarget() try to create a new log object if the
188 static void DontCreateOnDemand();
190 // log the count of repeating messages instead of logging the messages
192 static void SetRepetitionCounting(bool bRepetCounting
= true)
193 { ms_bRepetCounting
= bRepetCounting
; }
195 // gets duplicate counting status
196 static bool GetRepetitionCounting() { return ms_bRepetCounting
; }
198 // trace mask (see wxTraceXXX constants for details)
199 static void SetTraceMask(wxTraceMask ulMask
) { ms_ulTraceMask
= ulMask
; }
201 // add string trace mask
202 static void AddTraceMask(const wxString
& str
)
203 { ms_aTraceMasks
.push_back(str
); }
205 // add string trace mask
206 static void RemoveTraceMask(const wxString
& str
);
208 // remove all string trace masks
209 static void ClearTraceMasks();
211 // get string trace masks
212 static const wxArrayString
&GetTraceMasks() { return ms_aTraceMasks
; }
214 // sets the timestamp string: this is used as strftime() format string
215 // for the log targets which add time stamps to the messages - set it
216 // to NULL to disable time stamping completely.
217 static void SetTimestamp(const wxChar
*ts
) { ms_timestamp
= ts
; }
222 // gets the verbose status
223 static bool GetVerbose() { return ms_bVerbose
; }
226 static wxTraceMask
GetTraceMask() { return ms_ulTraceMask
; }
228 // is this trace mask in the list?
229 static bool IsAllowedTraceMask(const wxChar
*mask
);
231 // return the current loglevel limit
232 static wxLogLevel
GetLogLevel() { return ms_logLevel
; }
234 // get the current timestamp format string (may be NULL)
235 static const wxChar
*GetTimestamp() { return ms_timestamp
; }
240 // put the time stamp into the string if ms_timestamp != NULL (don't
241 // change it otherwise)
242 static void TimeStamp(wxString
*str
);
244 // make dtor virtual for all derived classes
248 // this method exists for backwards compatibility only, don't use
249 bool HasPendingMessages() const { return true; }
252 // the logging functions that can be overriden
254 // default DoLog() prepends the time stamp and a prefix corresponding
255 // to the message to szString and then passes it to DoLogString()
256 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
258 // default DoLogString does nothing but is not pure virtual because if
259 // you override DoLog() you might not need it at all
260 virtual void DoLogString(const wxChar
*szString
, time_t t
);
262 // log a line containing the number of times the previous message was
264 // returns: the number
265 static unsigned DoLogNumberOfRepeats();
271 // traditional behaviour or counting repetitions
272 static bool ms_bRepetCounting
;
273 static wxString ms_prevString
; // previous message that was logged
274 // how many times the previous message was logged
275 static unsigned ms_prevCounter
;
276 static time_t ms_prevTimeStamp
;// timestamp of the previous message
277 static wxLogLevel ms_prevLevel
; // level of the previous message
279 static wxLog
*ms_pLogger
; // currently active log sink
280 static bool ms_doLog
; // false => all logging disabled
281 static bool ms_bAutoCreate
; // create new log targets on demand?
282 static bool ms_bVerbose
; // false => ignore LogInfo messages
284 static wxLogLevel ms_logLevel
; // limit logging to levels <= ms_logLevel
286 static size_t ms_suspendCount
; // if positive, logs are not flushed
288 // format string for strftime(), if NULL, time stamping log messages is
290 static const wxChar
*ms_timestamp
;
292 static wxTraceMask ms_ulTraceMask
; // controls wxLogTrace behaviour
293 static wxArrayString ms_aTraceMasks
; // more powerful filter for wxLogTrace
296 // ----------------------------------------------------------------------------
297 // "trivial" derivations of wxLog
298 // ----------------------------------------------------------------------------
300 // log everything to a buffer
301 class WXDLLIMPEXP_BASE wxLogBuffer
: public wxLog
306 // get the string contents with all messages logged
307 const wxString
& GetBuffer() const { return m_str
; }
309 // show the buffer contents to the user in the best possible way (this uses
310 // wxMessageOutputMessageBox) and clear it
311 virtual void Flush();
314 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
315 virtual void DoLogString(const wxChar
*szString
, time_t t
);
320 DECLARE_NO_COPY_CLASS(wxLogBuffer
)
324 // log everything to a "FILE *", stderr by default
325 class WXDLLIMPEXP_BASE wxLogStderr
: public wxLog
328 // redirect log output to a FILE
329 wxLogStderr(FILE *fp
= (FILE *) NULL
);
332 // implement sink function
333 virtual void DoLogString(const wxChar
*szString
, time_t t
);
337 DECLARE_NO_COPY_CLASS(wxLogStderr
)
340 #if wxUSE_STD_IOSTREAM
342 // log everything to an "ostream", cerr by default
343 class WXDLLIMPEXP_BASE wxLogStream
: public wxLog
346 // redirect log output to an ostream
347 wxLogStream(wxSTD ostream
*ostr
= (wxSTD ostream
*) NULL
);
350 // implement sink function
351 virtual void DoLogString(const wxChar
*szString
, time_t t
);
353 // using ptr here to avoid including <iostream.h> from this file
354 wxSTD ostream
*m_ostr
;
357 #endif // wxUSE_STD_IOSTREAM
359 // ----------------------------------------------------------------------------
360 // /dev/null log target: suppress logging until this object goes out of scope
361 // ----------------------------------------------------------------------------
369 // wxFile.Open() normally complains if file can't be opened, we don't
373 if ( !file.Open("bar") )
374 ... process error ourselves ...
376 // ~wxLogNull called, old log sink restored
379 class WXDLLIMPEXP_BASE wxLogNull
382 wxLogNull() : m_flagOld(wxLog::EnableLogging(false)) { }
383 ~wxLogNull() { (void)wxLog::EnableLogging(m_flagOld
); }
386 bool m_flagOld
; // the previous value of the wxLog::ms_doLog
389 // ----------------------------------------------------------------------------
390 // chaining log target: installs itself as a log target and passes all
391 // messages to the real log target given to it in the ctor but also forwards
392 // them to the previously active one
394 // note that you don't have to call SetActiveTarget() with this class, it
395 // does it itself in its ctor
396 // ----------------------------------------------------------------------------
398 class WXDLLIMPEXP_BASE wxLogChain
: public wxLog
401 wxLogChain(wxLog
*logger
);
402 virtual ~wxLogChain();
404 // change the new log target
405 void SetLog(wxLog
*logger
);
407 // this can be used to temporarily disable (and then reenable) passing
408 // messages to the old logger (by default we do pass them)
409 void PassMessages(bool bDoPass
) { m_bPassMessages
= bDoPass
; }
411 // are we passing the messages to the previous log target?
412 bool IsPassingMessages() const { return m_bPassMessages
; }
414 // return the previous log target (may be NULL)
415 wxLog
*GetOldLog() const { return m_logOld
; }
417 // override base class version to flush the old logger as well
418 virtual void Flush();
421 // pass the chain to the old logger if needed
422 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
425 // the current log target
428 // the previous log target
431 // do we pass the messages to the old logger?
432 bool m_bPassMessages
;
434 DECLARE_NO_COPY_CLASS(wxLogChain
)
437 // a chain log target which uses itself as the new logger
438 class WXDLLIMPEXP_BASE wxLogPassThrough
: public wxLogChain
444 DECLARE_NO_COPY_CLASS(wxLogPassThrough
)
448 // include GUI log targets:
449 #include "wx/generic/logg.h"
452 // ============================================================================
454 // ============================================================================
456 // ----------------------------------------------------------------------------
457 // Log functions should be used by application instead of stdio, iostream &c
458 // for log messages for easy redirection
459 // ----------------------------------------------------------------------------
461 // ----------------------------------------------------------------------------
462 // get error code/error message from system in a portable way
463 // ----------------------------------------------------------------------------
465 // return the last system error code
466 WXDLLIMPEXP_BASE
unsigned long wxSysErrorCode();
468 // return the error message for given (or last if 0) error code
469 WXDLLIMPEXP_BASE
const wxChar
* wxSysErrorMsg(unsigned long nErrCode
= 0);
471 // ----------------------------------------------------------------------------
472 // define wxLog<level>
473 // ----------------------------------------------------------------------------
475 #define DECLARE_LOG_FUNCTION(level) \
476 extern void WXDLLIMPEXP_BASE wxVLog##level(const wxChar *szFormat, \
478 extern void WXDLLIMPEXP_BASE wxLog##level(const wxChar *szFormat, \
479 ...) ATTRIBUTE_PRINTF_1
480 #define DECLARE_LOG_FUNCTION2_EXP(level, argclass, arg, expdecl) \
481 extern void expdecl wxVLog##level(argclass arg, \
482 const wxChar *szFormat, \
484 extern void expdecl wxLog##level(argclass arg, \
485 const wxChar *szFormat, \
486 ...) ATTRIBUTE_PRINTF_2
489 // log functions do nothing at all
490 #define DECLARE_LOG_FUNCTION(level) \
491 inline void wxVLog##level(const wxChar *WXUNUSED(szFormat), \
492 va_list WXUNUSED(argptr)) { } \
493 inline void wxLog##level(const wxChar *WXUNUSED(szFormat), \
495 #define DECLARE_LOG_FUNCTION2_EXP(level, argclass, arg, expdecl) \
496 inline void wxVLog##level(argclass WXUNUSED(arg), \
497 const wxChar *WXUNUSED(szFormat), \
498 va_list WXUNUSED(argptr)) {} \
499 inline void wxLog##level(argclass WXUNUSED(arg), \
500 const wxChar *WXUNUSED(szFormat), \
503 // Empty Class to fake wxLogNull
504 class WXDLLIMPEXP_BASE wxLogNull
510 // Dummy macros to replace some functions.
511 #define wxSysErrorCode() (unsigned long)0
512 #define wxSysErrorMsg( X ) (const wxChar*)NULL
514 // Fake symbolic trace masks... for those that are used frequently
515 #define wxTRACE_OleCalls wxEmptyString // OLE interface calls
517 #endif // wxUSE_LOG/!wxUSE_LOG
519 #define DECLARE_LOG_FUNCTION2(level, argclass, arg) \
520 DECLARE_LOG_FUNCTION2_EXP(level, argclass, arg, WXDLLIMPEXP_BASE)
523 // a generic function for all levels (level is passes as parameter)
524 DECLARE_LOG_FUNCTION2(Generic
, wxLogLevel
, level
);
526 // one function per each level
527 DECLARE_LOG_FUNCTION(FatalError
);
528 DECLARE_LOG_FUNCTION(Error
);
529 DECLARE_LOG_FUNCTION(Warning
);
530 DECLARE_LOG_FUNCTION(Message
);
531 DECLARE_LOG_FUNCTION(Info
);
532 DECLARE_LOG_FUNCTION(Verbose
);
534 // this function sends the log message to the status line of the top level
535 // application frame, if any
536 DECLARE_LOG_FUNCTION(Status
);
539 // this one is the same as previous except that it allows to explicitly
540 class WXDLLEXPORT wxFrame
;
541 // specify the frame to which the output should go
542 DECLARE_LOG_FUNCTION2_EXP(Status
, wxFrame
*, pFrame
, WXDLLIMPEXP_CORE
);
545 // additional one: as wxLogError, but also logs last system call error code
546 // and the corresponding error message if available
547 DECLARE_LOG_FUNCTION(SysError
);
549 // and another one which also takes the error code (for those broken APIs
550 // that don't set the errno (like registry APIs in Win32))
551 DECLARE_LOG_FUNCTION2(SysError
, long, lErrCode
);
553 // debug functions do nothing in release mode
554 #if wxUSE_LOG && wxUSE_LOG_DEBUG
555 DECLARE_LOG_FUNCTION(Debug
);
557 // there is no more unconditional LogTrace: it is not different from
558 // LogDebug and it creates overload ambiguities
559 //DECLARE_LOG_FUNCTION(Trace);
561 // this version only logs the message if the mask had been added to the
562 // list of masks with AddTraceMask()
563 DECLARE_LOG_FUNCTION2(Trace
, const wxChar
*, mask
);
565 // and this one does nothing if all of level bits are not set in
566 // wxLog::GetActive()->GetTraceMask() -- it's deprecated in favour of
567 // string identifiers
568 DECLARE_LOG_FUNCTION2(Trace
, wxTraceMask
, mask
);
569 #else //!debug || !wxUSE_LOG
570 // these functions do nothing in release builds
572 // note that leaving out "fmt" in the vararg functions provokes a warning
573 // from SGI CC: "the last argument of the varargs function is unnamed"
574 inline void wxVLogDebug(const wxChar
*, va_list) { }
575 inline void wxLogDebug(const wxChar
*fmt
, ...) { wxUnusedVar(fmt
); }
576 inline void wxVLogTrace(wxTraceMask
, const wxChar
*, va_list) { }
577 inline void wxLogTrace(wxTraceMask
, const wxChar
*fmt
, ...) { wxUnusedVar(fmt
); }
578 inline void wxVLogTrace(const wxChar
*, const wxChar
*, va_list) { }
579 inline void wxLogTrace(const wxChar
*, const wxChar
*fmt
, ...) { wxUnusedVar(fmt
); }
580 #endif // debug/!debug
582 // wxLogFatalError helper: show the (fatal) error to the user in a safe way,
583 // i.e. without using wxMessageBox() for example because it could crash
584 void WXDLLIMPEXP_BASE
585 wxSafeShowMessage(const wxString
& title
, const wxString
& text
);
587 // ----------------------------------------------------------------------------
588 // debug only logging functions: use them with API name and error code
589 // ----------------------------------------------------------------------------
592 // make life easier for people using VC++ IDE: clicking on the message
593 // will take us immediately to the place of the failed API
595 #define wxLogApiError(api, rc) \
596 wxLogDebug(wxT("%s(%d): '%s' failed with error 0x%08lx (%s)."), \
597 __TFILE__, __LINE__, api, \
598 (long)rc, wxSysErrorMsg(rc))
600 #define wxLogApiError(api, rc) \
601 wxLogDebug(wxT("In file %s at line %d: '%s' failed with ") \
602 wxT("error 0x%08lx (%s)."), \
603 __TFILE__, __LINE__, api, \
604 (long)rc, wxSysErrorMsg(rc))
607 #define wxLogLastError(api) wxLogApiError(api, wxSysErrorCode())
610 inline void wxLogApiError(const wxChar
*, long) { }
611 inline void wxLogLastError(const wxChar
*) { }
612 #endif //debug/!debug
614 // wxCocoa has additiional trace masks
615 #if defined(__WXCOCOA__)
616 #include "wx/cocoa/log.h"