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 // ----------------------------------------------------------------------------
33 #include "wx/string.h"
37 #include "wx/arrstr.h"
40 #include <time.h> // for time_t
43 #include "wx/dynarray.h"
45 #ifndef wxUSE_LOG_DEBUG
47 # define wxUSE_LOG_DEBUG 1
48 # else // !__WXDEBUG__
49 # define wxUSE_LOG_DEBUG 0
53 // ----------------------------------------------------------------------------
54 // forward declarations
55 // ----------------------------------------------------------------------------
58 class WXDLLIMPEXP_CORE wxTextCtrl
;
59 class WXDLLIMPEXP_CORE wxLogFrame
;
60 class WXDLLIMPEXP_CORE wxFrame
;
63 // ----------------------------------------------------------------------------
65 // ----------------------------------------------------------------------------
67 // different standard log levels (you may also define your own)
70 wxLOG_FatalError
, // program can't continue, abort immediately
71 wxLOG_Error
, // a serious error, user must be informed about it
72 wxLOG_Warning
, // user is normally informed about it but may be ignored
73 wxLOG_Message
, // normal message (i.e. normal output of a non GUI app)
74 wxLOG_Status
, // informational: might go to the status line of GUI app
75 wxLOG_Info
, // informational message (a.k.a. 'Verbose')
76 wxLOG_Debug
, // never shown to the user, disabled in release mode
77 wxLOG_Trace
, // trace messages are also only enabled in debug mode
78 wxLOG_Progress
, // used for progress indicator (not yet)
79 wxLOG_User
= 100, // user defined levels start here
83 // symbolic trace masks - wxLogTrace("foo", "some trace message...") will be
84 // discarded unless the string "foo" has been added to the list of allowed
85 // ones with AddTraceMask()
87 #define wxTRACE_MemAlloc wxT("memalloc") // trace memory allocation (new/delete)
88 #define wxTRACE_Messages wxT("messages") // trace window messages/X callbacks
89 #define wxTRACE_ResAlloc wxT("resalloc") // trace GDI resource allocation
90 #define wxTRACE_RefCount wxT("refcount") // trace various ref counting operations
93 #define wxTRACE_OleCalls wxT("ole") // OLE interface calls
96 // the trace masks have been superceded by symbolic trace constants, they're
97 // for compatibility only andwill be removed soon - do NOT use them
99 // meaning of different bits of the trace mask (which allows selectively
100 // enable/disable some trace messages)
101 #define wxTraceMemAlloc 0x0001 // trace memory allocation (new/delete)
102 #define wxTraceMessages 0x0002 // trace window messages/X callbacks
103 #define wxTraceResAlloc 0x0004 // trace GDI resource allocation
104 #define wxTraceRefCount 0x0008 // trace various ref counting operations
107 #define wxTraceOleCalls 0x0100 // OLE interface calls
110 #include "wx/iosfwrap.h"
112 // ----------------------------------------------------------------------------
113 // derive from this class to redirect (or suppress, or ...) log messages
114 // normally, only a single instance of this class exists but it's not enforced
115 // ----------------------------------------------------------------------------
117 class WXDLLIMPEXP_BASE wxLog
125 // Allow replacement of the fixed size static buffer with
126 // a user allocated one. Pass in NULL to restore the
127 // built in static buffer.
128 static wxChar
*SetLogBuffer( wxChar
*buf
, size_t size
= 0 );
130 // these functions allow to completely disable all log messages
132 // is logging disabled now?
133 static bool IsEnabled() { return ms_doLog
; }
135 // change the flag state, return the previous one
136 static bool EnableLogging(bool doIt
= true)
137 { bool doLogOld
= ms_doLog
; ms_doLog
= doIt
; return doLogOld
; }
139 // static sink function - see DoLog() for function to overload in the
141 static void OnLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
143 if ( IsEnabled() && ms_logLevel
>= level
)
145 wxLog
*pLogger
= GetActiveTarget();
147 pLogger
->DoLog(level
, szString
, t
);
153 // flush shows all messages if they're not logged immediately (FILE
154 // and iostream logs don't need it, but wxGuiLog does to avoid showing
155 // 17 modal dialogs one after another)
156 virtual void Flush();
158 // flush the active target if any
159 static void FlushActive()
161 if ( !ms_suspendCount
)
163 wxLog
*log
= GetActiveTarget();
169 // only one sink is active at each moment
170 // get current log target, will call wxApp::CreateLogTarget() to
171 // create one if none exists
172 static wxLog
*GetActiveTarget();
174 // change log target, pLogger may be NULL
175 static wxLog
*SetActiveTarget(wxLog
*pLogger
);
177 // suspend the message flushing of the main target until the next call
178 // to Resume() - this is mainly for internal use (to prevent wxYield()
179 // from flashing the messages)
180 static void Suspend() { ms_suspendCount
++; }
182 // must be called for each Suspend()!
183 static void Resume() { ms_suspendCount
--; }
185 // functions controlling the default wxLog behaviour
186 // verbose mode is activated by standard command-line '-verbose'
188 static void SetVerbose(bool bVerbose
= true) { ms_bVerbose
= bVerbose
; }
190 // Set log level. Log messages with level > logLevel will not be logged.
191 static void SetLogLevel(wxLogLevel logLevel
) { ms_logLevel
= logLevel
; }
193 // should GetActiveTarget() try to create a new log object if the
195 static void DontCreateOnDemand();
197 // trace mask (see wxTraceXXX constants for details)
198 static void SetTraceMask(wxTraceMask ulMask
) { ms_ulTraceMask
= ulMask
; }
200 // add string trace mask
201 static void AddTraceMask(const wxString
& str
)
202 { ms_aTraceMasks
.push_back(str
); }
204 // add string trace mask
205 static void RemoveTraceMask(const wxString
& str
);
207 // remove all string trace masks
208 static void ClearTraceMasks();
210 // get string trace masks
211 static const wxArrayString
&GetTraceMasks() { return ms_aTraceMasks
; }
213 // sets the timestamp string: this is used as strftime() format string
214 // for the log targets which add time stamps to the messages - set it
215 // to NULL to disable time stamping completely.
216 static void SetTimestamp(const wxChar
*ts
) { ms_timestamp
= ts
; }
221 // gets the verbose status
222 static bool GetVerbose() { return ms_bVerbose
; }
225 static wxTraceMask
GetTraceMask() { return ms_ulTraceMask
; }
227 // is this trace mask in the list?
228 static bool IsAllowedTraceMask(const wxChar
*mask
);
230 // return the current loglevel limit
231 static wxLogLevel
GetLogLevel() { return ms_logLevel
; }
233 // get the current timestamp format string (may be NULL)
234 static const wxChar
*GetTimestamp() { return ms_timestamp
; }
239 // put the time stamp into the string if ms_timestamp != NULL (don't
240 // change it otherwise)
241 static void TimeStamp(wxString
*str
);
243 // make dtor virtual for all derived classes
247 // this method exists for backwards compatibility only, don't use
248 bool HasPendingMessages() const { return true; }
251 // the logging functions that can be overriden
253 // default DoLog() prepends the time stamp and a prefix corresponding
254 // to the message to szString and then passes it to DoLogString()
255 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
257 // default DoLogString does nothing but is not pure virtual because if
258 // you override DoLog() you might not need it at all
259 virtual void DoLogString(const wxChar
*szString
, time_t t
);
265 static wxLog
*ms_pLogger
; // currently active log sink
266 static bool ms_doLog
; // false => all logging disabled
267 static bool ms_bAutoCreate
; // create new log targets on demand?
268 static bool ms_bVerbose
; // false => ignore LogInfo messages
270 static wxLogLevel ms_logLevel
; // limit logging to levels <= ms_logLevel
272 static size_t ms_suspendCount
; // if positive, logs are not flushed
274 // format string for strftime(), if NULL, time stamping log messages is
276 static const wxChar
*ms_timestamp
;
278 static wxTraceMask ms_ulTraceMask
; // controls wxLogTrace behaviour
279 static wxArrayString ms_aTraceMasks
; // more powerful filter for wxLogTrace
282 // ----------------------------------------------------------------------------
283 // "trivial" derivations of wxLog
284 // ----------------------------------------------------------------------------
286 // log everything to a "FILE *", stderr by default
287 class WXDLLIMPEXP_BASE wxLogStderr
: public wxLog
289 DECLARE_NO_COPY_CLASS(wxLogStderr
)
292 // redirect log output to a FILE
293 wxLogStderr(FILE *fp
= (FILE *) NULL
);
296 // implement sink function
297 virtual void DoLogString(const wxChar
*szString
, time_t t
);
302 #if wxUSE_STD_IOSTREAM
304 // log everything to an "ostream", cerr by default
305 class WXDLLIMPEXP_BASE wxLogStream
: public wxLog
308 // redirect log output to an ostream
309 wxLogStream(wxSTD ostream
*ostr
= (wxSTD ostream
*) NULL
);
312 // implement sink function
313 virtual void DoLogString(const wxChar
*szString
, time_t t
);
315 // using ptr here to avoid including <iostream.h> from this file
316 wxSTD ostream
*m_ostr
;
319 #endif // wxUSE_STD_IOSTREAM
321 // ----------------------------------------------------------------------------
322 // /dev/null log target: suppress logging until this object goes out of scope
323 // ----------------------------------------------------------------------------
331 // wxFile.Open() normally complains if file can't be opened, we don't
335 if ( !file.Open("bar") )
336 ... process error ourselves ...
338 // ~wxLogNull called, old log sink restored
341 class WXDLLIMPEXP_BASE wxLogNull
344 wxLogNull() : m_flagOld(wxLog::EnableLogging(false)) { }
345 ~wxLogNull() { (void)wxLog::EnableLogging(m_flagOld
); }
348 bool m_flagOld
; // the previous value of the wxLog::ms_doLog
351 // ----------------------------------------------------------------------------
352 // chaining log target: installs itself as a log target and passes all
353 // messages to the real log target given to it in the ctor but also forwards
354 // them to the previously active one
356 // note that you don't have to call SetActiveTarget() with this class, it
357 // does it itself in its ctor
358 // ----------------------------------------------------------------------------
360 class WXDLLIMPEXP_BASE wxLogChain
: public wxLog
363 wxLogChain(wxLog
*logger
);
364 virtual ~wxLogChain();
366 // change the new log target
367 void SetLog(wxLog
*logger
);
369 // this can be used to temporarily disable (and then reenable) passing
370 // messages to the old logger (by default we do pass them)
371 void PassMessages(bool bDoPass
) { m_bPassMessages
= bDoPass
; }
373 // are we passing the messages to the previous log target?
374 bool IsPassingMessages() const { return m_bPassMessages
; }
376 // return the previous log target (may be NULL)
377 wxLog
*GetOldLog() const { return m_logOld
; }
379 // override base class version to flush the old logger as well
380 virtual void Flush();
383 // pass the chain to the old logger if needed
384 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
387 // the current log target
390 // the previous log target
393 // do we pass the messages to the old logger?
394 bool m_bPassMessages
;
396 DECLARE_NO_COPY_CLASS(wxLogChain
)
399 // a chain log target which uses itself as the new logger
400 class WXDLLIMPEXP_BASE wxLogPassThrough
: public wxLogChain
406 DECLARE_NO_COPY_CLASS(wxLogPassThrough
)
410 // include GUI log targets:
411 #include "wx/generic/logg.h"
414 // ============================================================================
416 // ============================================================================
418 // ----------------------------------------------------------------------------
419 // Log functions should be used by application instead of stdio, iostream &c
420 // for log messages for easy redirection
421 // ----------------------------------------------------------------------------
423 // ----------------------------------------------------------------------------
424 // get error code/error message from system in a portable way
425 // ----------------------------------------------------------------------------
427 // return the last system error code
428 WXDLLIMPEXP_BASE
unsigned long wxSysErrorCode();
430 // return the error message for given (or last if 0) error code
431 WXDLLIMPEXP_BASE
const wxChar
* wxSysErrorMsg(unsigned long nErrCode
= 0);
433 // ----------------------------------------------------------------------------
434 // define wxLog<level>
435 // ----------------------------------------------------------------------------
437 #define DECLARE_LOG_FUNCTION(level) \
438 extern void WXDLLIMPEXP_BASE wxVLog##level(const wxChar *szFormat, \
440 extern void WXDLLIMPEXP_BASE wxLog##level(const wxChar *szFormat, \
441 ...) ATTRIBUTE_PRINTF_1
442 #define DECLARE_LOG_FUNCTION2_EXP(level, arg, expdecl) \
443 extern void expdecl wxVLog##level(arg, const wxChar *szFormat, \
445 extern void expdecl wxLog##level(arg, const wxChar *szFormat, \
446 ...) ATTRIBUTE_PRINTF_2
447 #define DECLARE_LOG_FUNCTION2(level, arg) \
448 DECLARE_LOG_FUNCTION2_EXP(level, arg, WXDLLIMPEXP_BASE)
452 // log functions do nothing at all
453 #define DECLARE_LOG_FUNCTION(level) \
454 inline void wxVLog##level(const wxChar *szFormat, \
455 va_list argptr) { } \
456 inline void wxLog##level(const wxChar *szFormat, ...) { }
457 #define DECLARE_LOG_FUNCTION2(level, arg) \
458 inline void wxVLog##level(arg, const wxChar *szFormat, \
460 inline void wxLog##level(arg, const wxChar *szFormat, ...) { }
462 // Empty Class to fake wxLogNull
463 class WXDLLIMPEXP_BASE wxLogNull
469 // Dummy macros to replace some functions.
470 #define wxSysErrorCode() (unsigned long)0
471 #define wxSysErrorMsg( X ) (const wxChar*)NULL
473 // Fake symbolic trace masks... for those that are used frequently
474 #define wxTRACE_OleCalls wxEmptyString // OLE interface calls
476 #endif // wxUSE_LOG/!wxUSE_LOG
478 // a generic function for all levels (level is passes as parameter)
479 DECLARE_LOG_FUNCTION2(Generic
, wxLogLevel level
);
481 // one function per each level
482 DECLARE_LOG_FUNCTION(FatalError
);
483 DECLARE_LOG_FUNCTION(Error
);
484 DECLARE_LOG_FUNCTION(Warning
);
485 DECLARE_LOG_FUNCTION(Message
);
486 DECLARE_LOG_FUNCTION(Info
);
487 DECLARE_LOG_FUNCTION(Verbose
);
489 // this function sends the log message to the status line of the top level
490 // application frame, if any
491 DECLARE_LOG_FUNCTION(Status
);
494 // this one is the same as previous except that it allows to explicitly
495 // specify the frame to which the output should go
496 DECLARE_LOG_FUNCTION2_EXP(Status
, wxFrame
*pFrame
, WXDLLIMPEXP_CORE
);
499 // additional one: as wxLogError, but also logs last system call error code
500 // and the corresponding error message if available
501 DECLARE_LOG_FUNCTION(SysError
);
503 // and another one which also takes the error code (for those broken APIs
504 // that don't set the errno (like registry APIs in Win32))
505 DECLARE_LOG_FUNCTION2(SysError
, long lErrCode
);
507 // debug functions do nothing in release mode
509 DECLARE_LOG_FUNCTION(Debug
);
511 // there is no more unconditional LogTrace: it is not different from
512 // LogDebug and it creates overload ambiguities
513 //DECLARE_LOG_FUNCTION(Trace);
515 // this version only logs the message if the mask had been added to the
516 // list of masks with AddTraceMask()
517 DECLARE_LOG_FUNCTION2(Trace
, const wxChar
*mask
);
519 // and this one does nothing if all of level bits are not set in
520 // wxLog::GetActive()->GetTraceMask() -- it's deprecated in favour of
521 // string identifiers
522 DECLARE_LOG_FUNCTION2(Trace
, wxTraceMask mask
);
524 // these functions do nothing in release builds
525 inline void wxVLogDebug(const wxChar
*, va_list) { }
526 inline void wxLogDebug(const wxChar
*, ...) { }
527 inline void wxVLogTrace(wxTraceMask
, const wxChar
*, va_list) { }
528 inline void wxLogTrace(wxTraceMask
, const wxChar
*, ...) { }
529 inline void wxVLogTrace(const wxChar
*, const wxChar
*, va_list) { }
530 inline void wxLogTrace(const wxChar
*, const wxChar
*, ...) { }
531 #endif // debug/!debug
533 // wxLogFatalError helper: show the (fatal) error to the user in a safe way,
534 // i.e. without using wxMessageBox() for example because it could crash
535 void WXDLLIMPEXP_BASE
536 wxSafeShowMessage(const wxString
& title
, const wxString
& text
);
538 // ----------------------------------------------------------------------------
539 // debug only logging functions: use them with API name and error code
540 // ----------------------------------------------------------------------------
543 // make life easier for people using VC++ IDE: clicking on the message
544 // will take us immediately to the place of the failed API
546 #define wxLogApiError(api, rc) \
547 wxLogDebug(wxT("%s(%d): '%s' failed with error 0x%08lx (%s)."), \
548 __TFILE__, __LINE__, api, \
549 (long)rc, wxSysErrorMsg(rc))
551 #define wxLogApiError(api, rc) \
552 wxLogDebug(wxT("In file %s at line %d: '%s' failed with ") \
553 wxT("error 0x%08lx (%s)."), \
554 __TFILE__, __LINE__, api, \
555 (long)rc, wxSysErrorMsg(rc))
558 #define wxLogLastError(api) wxLogApiError(api, wxSysErrorCode())
561 inline void wxLogApiError(const wxChar
*, long) { }
562 inline void wxLogLastError(const wxChar
*) { }
563 #endif //debug/!debug
565 // wxCocoa has additiional trace masks
566 #if defined(__WXCOCOA__)
567 #include "wx/cocoa/log.h"