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 // ----------------------------------------------------------------------------
23 // ----------------------------------------------------------------------------
25 // NB: these types are needed even if wxUSE_LOG == 0
26 typedef unsigned long wxTraceMask
;
27 typedef unsigned long wxLogLevel
;
29 // ----------------------------------------------------------------------------
31 // ----------------------------------------------------------------------------
35 #include "wx/string.h"
36 #include "wx/arrstr.h"
39 #include <time.h> // for time_t
42 #include "wx/dynarray.h"
44 #ifndef wxUSE_LOG_DEBUG
46 # define wxUSE_LOG_DEBUG 1
47 # else // !__WXDEBUG__
48 # define wxUSE_LOG_DEBUG 0
52 // ----------------------------------------------------------------------------
53 // forward declarations
54 // ----------------------------------------------------------------------------
57 class WXDLLIMPEXP_CORE wxTextCtrl
;
58 class WXDLLIMPEXP_CORE wxLogFrame
;
59 class WXDLLIMPEXP_CORE wxFrame
;
62 // ----------------------------------------------------------------------------
64 // ----------------------------------------------------------------------------
66 // different standard log levels (you may also define your own)
69 wxLOG_FatalError
, // program can't continue, abort immediately
70 wxLOG_Error
, // a serious error, user must be informed about it
71 wxLOG_Warning
, // user is normally informed about it but may be ignored
72 wxLOG_Message
, // normal message (i.e. normal output of a non GUI app)
73 wxLOG_Status
, // informational: might go to the status line of GUI app
74 wxLOG_Info
, // informational message (a.k.a. 'Verbose')
75 wxLOG_Debug
, // never shown to the user, disabled in release mode
76 wxLOG_Trace
, // trace messages are also only enabled in debug mode
77 wxLOG_Progress
, // used for progress indicator (not yet)
78 wxLOG_User
= 100, // user defined levels start here
82 // symbolic trace masks - wxLogTrace("foo", "some trace message...") will be
83 // discarded unless the string "foo" has been added to the list of allowed
84 // ones with AddTraceMask()
86 #define wxTRACE_MemAlloc wxT("memalloc") // trace memory allocation (new/delete)
87 #define wxTRACE_Messages wxT("messages") // trace window messages/X callbacks
88 #define wxTRACE_ResAlloc wxT("resalloc") // trace GDI resource allocation
89 #define wxTRACE_RefCount wxT("refcount") // trace various ref counting operations
92 #define wxTRACE_OleCalls wxT("ole") // OLE interface calls
95 // the trace masks have been superceded by symbolic trace constants, they're
96 // for compatibility only andwill be removed soon - do NOT use them
98 // meaning of different bits of the trace mask (which allows selectively
99 // enable/disable some trace messages)
100 #define wxTraceMemAlloc 0x0001 // trace memory allocation (new/delete)
101 #define wxTraceMessages 0x0002 // trace window messages/X callbacks
102 #define wxTraceResAlloc 0x0004 // trace GDI resource allocation
103 #define wxTraceRefCount 0x0008 // trace various ref counting operations
106 #define wxTraceOleCalls 0x0100 // OLE interface calls
109 #include "wx/iosfwrap.h"
111 // ----------------------------------------------------------------------------
112 // derive from this class to redirect (or suppress, or ...) log messages
113 // normally, only a single instance of this class exists but it's not enforced
114 // ----------------------------------------------------------------------------
116 class WXDLLIMPEXP_BASE wxLog
124 // Allow replacement of the fixed size static buffer with
125 // a user allocated one. Pass in NULL to restore the
126 // built in static buffer.
127 static wxChar
*SetLogBuffer( wxChar
*buf
, size_t size
= 0 );
129 // these functions allow to completely disable all log messages
131 // is logging disabled now?
132 static bool IsEnabled() { return ms_doLog
; }
134 // change the flag state, return the previous one
135 static bool EnableLogging(bool doIt
= true)
136 { bool doLogOld
= ms_doLog
; ms_doLog
= doIt
; return doLogOld
; }
138 // static sink function - see DoLog() for function to overload in the
140 static void OnLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
142 if ( IsEnabled() && ms_logLevel
>= level
)
144 wxLog
*pLogger
= GetActiveTarget();
146 pLogger
->DoLog(level
, szString
, t
);
152 // flush shows all messages if they're not logged immediately (FILE
153 // and iostream logs don't need it, but wxGuiLog does to avoid showing
154 // 17 modal dialogs one after another)
155 virtual void Flush();
157 // flush the active target if any
158 static void FlushActive()
160 if ( !ms_suspendCount
)
162 wxLog
*log
= GetActiveTarget();
168 // only one sink is active at each moment
169 // get current log target, will call wxApp::CreateLogTarget() to
170 // create one if none exists
171 static wxLog
*GetActiveTarget();
173 // change log target, pLogger may be NULL
174 static wxLog
*SetActiveTarget(wxLog
*pLogger
);
176 // suspend the message flushing of the main target until the next call
177 // to Resume() - this is mainly for internal use (to prevent wxYield()
178 // from flashing the messages)
179 static void Suspend() { ms_suspendCount
++; }
181 // must be called for each Suspend()!
182 static void Resume() { ms_suspendCount
--; }
184 // functions controlling the default wxLog behaviour
185 // verbose mode is activated by standard command-line '-verbose'
187 static void SetVerbose(bool bVerbose
= true) { ms_bVerbose
= bVerbose
; }
189 // Set log level. Log messages with level > logLevel will not be logged.
190 static void SetLogLevel(wxLogLevel logLevel
) { ms_logLevel
= logLevel
; }
192 // should GetActiveTarget() try to create a new log object if the
194 static void DontCreateOnDemand();
196 // trace mask (see wxTraceXXX constants for details)
197 static void SetTraceMask(wxTraceMask ulMask
) { ms_ulTraceMask
= ulMask
; }
199 // add string trace mask
200 static void AddTraceMask(const wxString
& str
)
201 { ms_aTraceMasks
.push_back(str
); }
203 // add string trace mask
204 static void RemoveTraceMask(const wxString
& str
);
206 // remove all string trace masks
207 static void ClearTraceMasks();
209 // get string trace masks
210 static const wxArrayString
&GetTraceMasks() { return ms_aTraceMasks
; }
212 // sets the timestamp string: this is used as strftime() format string
213 // for the log targets which add time stamps to the messages - set it
214 // to NULL to disable time stamping completely.
215 static void SetTimestamp(const wxChar
*ts
) { ms_timestamp
= ts
; }
220 // gets the verbose status
221 static bool GetVerbose() { return ms_bVerbose
; }
224 static wxTraceMask
GetTraceMask() { return ms_ulTraceMask
; }
226 // is this trace mask in the list?
227 static bool IsAllowedTraceMask(const wxChar
*mask
);
229 // return the current loglevel limit
230 static wxLogLevel
GetLogLevel() { return ms_logLevel
; }
232 // get the current timestamp format string (may be NULL)
233 static const wxChar
*GetTimestamp() { return ms_timestamp
; }
238 // put the time stamp into the string if ms_timestamp != NULL (don't
239 // change it otherwise)
240 static void TimeStamp(wxString
*str
);
242 // make dtor virtual for all derived classes
246 // this method exists for backwards compatibility only, don't use
247 bool HasPendingMessages() const { return true; }
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
);
264 static wxLog
*ms_pLogger
; // currently active log sink
265 static bool ms_doLog
; // false => all logging disabled
266 static bool ms_bAutoCreate
; // create new log targets on demand?
267 static bool ms_bVerbose
; // false => ignore LogInfo messages
269 static wxLogLevel ms_logLevel
; // limit logging to levels <= ms_logLevel
271 static size_t ms_suspendCount
; // if positive, logs are not flushed
273 // format string for strftime(), if NULL, time stamping log messages is
275 static const wxChar
*ms_timestamp
;
277 static wxTraceMask ms_ulTraceMask
; // controls wxLogTrace behaviour
278 static wxArrayString ms_aTraceMasks
; // more powerful filter for wxLogTrace
281 // ----------------------------------------------------------------------------
282 // "trivial" derivations of wxLog
283 // ----------------------------------------------------------------------------
285 // log everything to a "FILE *", stderr by default
286 class WXDLLIMPEXP_BASE wxLogStderr
: public wxLog
288 DECLARE_NO_COPY_CLASS(wxLogStderr
)
291 // redirect log output to a FILE
292 wxLogStderr(FILE *fp
= (FILE *) NULL
);
295 // implement sink function
296 virtual void DoLogString(const wxChar
*szString
, time_t t
);
301 #if wxUSE_STD_IOSTREAM
303 // log everything to an "ostream", cerr by default
304 class WXDLLIMPEXP_BASE wxLogStream
: public wxLog
307 // redirect log output to an ostream
308 wxLogStream(wxSTD ostream
*ostr
= (wxSTD ostream
*) NULL
);
311 // implement sink function
312 virtual void DoLogString(const wxChar
*szString
, time_t t
);
314 // using ptr here to avoid including <iostream.h> from this file
315 wxSTD ostream
*m_ostr
;
318 #endif // wxUSE_STD_IOSTREAM
320 // ----------------------------------------------------------------------------
321 // /dev/null log target: suppress logging until this object goes out of scope
322 // ----------------------------------------------------------------------------
330 // wxFile.Open() normally complains if file can't be opened, we don't
334 if ( !file.Open("bar") )
335 ... process error ourselves ...
337 // ~wxLogNull called, old log sink restored
340 class WXDLLIMPEXP_BASE wxLogNull
343 wxLogNull() : m_flagOld(wxLog::EnableLogging(false)) { }
344 ~wxLogNull() { (void)wxLog::EnableLogging(m_flagOld
); }
347 bool m_flagOld
; // the previous value of the wxLog::ms_doLog
350 // ----------------------------------------------------------------------------
351 // chaining log target: installs itself as a log target and passes all
352 // messages to the real log target given to it in the ctor but also forwards
353 // them to the previously active one
355 // note that you don't have to call SetActiveTarget() with this class, it
356 // does it itself in its ctor
357 // ----------------------------------------------------------------------------
359 class WXDLLIMPEXP_BASE wxLogChain
: public wxLog
362 wxLogChain(wxLog
*logger
);
363 virtual ~wxLogChain();
365 // change the new log target
366 void SetLog(wxLog
*logger
);
368 // this can be used to temporarily disable (and then reenable) passing
369 // messages to the old logger (by default we do pass them)
370 void PassMessages(bool bDoPass
) { m_bPassMessages
= bDoPass
; }
372 // are we passing the messages to the previous log target?
373 bool IsPassingMessages() const { return m_bPassMessages
; }
375 // return the previous log target (may be NULL)
376 wxLog
*GetOldLog() const { return m_logOld
; }
378 // override base class version to flush the old logger as well
379 virtual void Flush();
382 // pass the chain to the old logger if needed
383 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
386 // the current log target
389 // the previous log target
392 // do we pass the messages to the old logger?
393 bool m_bPassMessages
;
395 DECLARE_NO_COPY_CLASS(wxLogChain
)
398 // a chain log target which uses itself as the new logger
399 class WXDLLIMPEXP_BASE wxLogPassThrough
: public wxLogChain
405 DECLARE_NO_COPY_CLASS(wxLogPassThrough
)
409 // include GUI log targets:
410 #include "wx/generic/logg.h"
413 // ============================================================================
415 // ============================================================================
417 // ----------------------------------------------------------------------------
418 // Log functions should be used by application instead of stdio, iostream &c
419 // for log messages for easy redirection
420 // ----------------------------------------------------------------------------
422 // ----------------------------------------------------------------------------
423 // get error code/error message from system in a portable way
424 // ----------------------------------------------------------------------------
426 // return the last system error code
427 WXDLLIMPEXP_BASE
unsigned long wxSysErrorCode();
429 // return the error message for given (or last if 0) error code
430 WXDLLIMPEXP_BASE
const wxChar
* wxSysErrorMsg(unsigned long nErrCode
= 0);
432 // ----------------------------------------------------------------------------
433 // define wxLog<level>
434 // ----------------------------------------------------------------------------
436 #define DECLARE_LOG_FUNCTION(level) \
437 extern void WXDLLIMPEXP_BASE wxVLog##level(const wxChar *szFormat, \
439 extern void WXDLLIMPEXP_BASE wxLog##level(const wxChar *szFormat, \
440 ...) ATTRIBUTE_PRINTF_1
441 #define DECLARE_LOG_FUNCTION2_EXP(level, arg, expdecl) \
442 extern void expdecl wxVLog##level(arg, const wxChar *szFormat, \
444 extern void expdecl wxLog##level(arg, const wxChar *szFormat, \
445 ...) ATTRIBUTE_PRINTF_2
446 #define DECLARE_LOG_FUNCTION2(level, arg) \
447 DECLARE_LOG_FUNCTION2_EXP(level, arg, WXDLLIMPEXP_BASE)
451 // log functions do nothing at all
452 #define DECLARE_LOG_FUNCTION(level) \
453 inline void wxVLog##level(const wxChar *szFormat, \
454 va_list argptr) { } \
455 inline void wxLog##level(const wxChar *szFormat, ...) { }
456 #define DECLARE_LOG_FUNCTION2(level, arg) \
457 inline void wxVLog##level(arg, const wxChar *szFormat, \
459 inline void wxLog##level(arg, const wxChar *szFormat, ...) { }
461 // Empty Class to fake wxLogNull
462 class WXDLLIMPEXP_BASE wxLogNull
468 // Dummy macros to replace some functions.
469 #define wxSysErrorCode() (unsigned long)0
470 #define wxSysErrorMsg( X ) (const wxChar*)NULL
472 // Fake symbolic trace masks... for those that are used frequently
473 #define wxTRACE_OleCalls wxEmptyString // OLE interface calls
475 #endif // wxUSE_LOG/!wxUSE_LOG
477 // a generic function for all levels (level is passes as parameter)
478 DECLARE_LOG_FUNCTION2(Generic
, wxLogLevel level
);
480 // one function per each level
481 DECLARE_LOG_FUNCTION(FatalError
);
482 DECLARE_LOG_FUNCTION(Error
);
483 DECLARE_LOG_FUNCTION(Warning
);
484 DECLARE_LOG_FUNCTION(Message
);
485 DECLARE_LOG_FUNCTION(Info
);
486 DECLARE_LOG_FUNCTION(Verbose
);
488 // this function sends the log message to the status line of the top level
489 // application frame, if any
490 DECLARE_LOG_FUNCTION(Status
);
493 // this one is the same as previous except that it allows to explicitly
494 // specify the frame to which the output should go
495 DECLARE_LOG_FUNCTION2_EXP(Status
, wxFrame
*pFrame
, WXDLLIMPEXP_CORE
);
498 // additional one: as wxLogError, but also logs last system call error code
499 // and the corresponding error message if available
500 DECLARE_LOG_FUNCTION(SysError
);
502 // and another one which also takes the error code (for those broken APIs
503 // that don't set the errno (like registry APIs in Win32))
504 DECLARE_LOG_FUNCTION2(SysError
, long lErrCode
);
506 // debug functions do nothing in release mode
508 DECLARE_LOG_FUNCTION(Debug
);
510 // there is no more unconditional LogTrace: it is not different from
511 // LogDebug and it creates overload ambiguities
512 //DECLARE_LOG_FUNCTION(Trace);
514 // this version only logs the message if the mask had been added to the
515 // list of masks with AddTraceMask()
516 DECLARE_LOG_FUNCTION2(Trace
, const wxChar
*mask
);
518 // and this one does nothing if all of level bits are not set in
519 // wxLog::GetActive()->GetTraceMask() -- it's deprecated in favour of
520 // string identifiers
521 DECLARE_LOG_FUNCTION2(Trace
, wxTraceMask mask
);
523 // these functions do nothing in release builds
524 inline void wxVLogDebug(const wxChar
*, va_list) { }
525 inline void wxLogDebug(const wxChar
*, ...) { }
526 inline void wxVLogTrace(wxTraceMask
, const wxChar
*, va_list) { }
527 inline void wxLogTrace(wxTraceMask
, const wxChar
*, ...) { }
528 inline void wxVLogTrace(const wxChar
*, const wxChar
*, va_list) { }
529 inline void wxLogTrace(const wxChar
*, const wxChar
*, ...) { }
530 #endif // debug/!debug
532 // wxLogFatalError helper: show the (fatal) error to the user in a safe way,
533 // i.e. without using wxMessageBox() for example because it could crash
534 void WXDLLIMPEXP_BASE
535 wxSafeShowMessage(const wxString
& title
, const wxString
& text
);
537 // ----------------------------------------------------------------------------
538 // debug only logging functions: use them with API name and error code
539 // ----------------------------------------------------------------------------
542 // make life easier for people using VC++ IDE: clicking on the message
543 // will take us immediately to the place of the failed API
545 #define wxLogApiError(api, rc) \
546 wxLogDebug(wxT("%s(%d): '%s' failed with error 0x%08lx (%s)."), \
547 __TFILE__, __LINE__, api, \
548 (long)rc, wxSysErrorMsg(rc))
550 #define wxLogApiError(api, rc) \
551 wxLogDebug(wxT("In file %s at line %d: '%s' failed with ") \
552 wxT("error 0x%08lx (%s)."), \
553 __TFILE__, __LINE__, api, \
554 (long)rc, wxSysErrorMsg(rc))
557 #define wxLogLastError(api) wxLogApiError(api, wxSysErrorCode())
560 inline void wxLogApiError(const wxChar
*, long) { }
561 inline void wxLogLastError(const wxChar
*) { }
562 #endif //debug/!debug
564 // wxCocoa has additiional trace masks
565 #if defined(__WXCOCOA__)
566 #include "wx/cocoa/log.h"