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"
23 #include "wx/string.h"
24 #include "wx/arrstr.h"
26 // ----------------------------------------------------------------------------
27 // forward declarations
28 // ----------------------------------------------------------------------------
31 class WXDLLIMPEXP_CORE wxTextCtrl
;
32 class WXDLLIMPEXP_CORE wxLogFrame
;
33 class WXDLLIMPEXP_CORE wxFrame
;
36 // ----------------------------------------------------------------------------
38 // ----------------------------------------------------------------------------
40 typedef unsigned long wxTraceMask
;
41 typedef unsigned long wxLogLevel
;
43 // ----------------------------------------------------------------------------
45 // ----------------------------------------------------------------------------
48 #include <time.h> // for time_t
51 #include "wx/dynarray.h"
53 #ifndef wxUSE_LOG_DEBUG
55 # define wxUSE_LOG_DEBUG 1
56 # else // !__WXDEBUG__
57 # define wxUSE_LOG_DEBUG 0
61 // ----------------------------------------------------------------------------
63 // ----------------------------------------------------------------------------
65 // different standard log levels (you may also define your own)
68 wxLOG_FatalError
, // program can't continue, abort immediately
69 wxLOG_Error
, // a serious error, user must be informed about it
70 wxLOG_Warning
, // user is normally informed about it but may be ignored
71 wxLOG_Message
, // normal message (i.e. normal output of a non GUI app)
72 wxLOG_Status
, // informational: might go to the status line of GUI app
73 wxLOG_Info
, // informational message (a.k.a. 'Verbose')
74 wxLOG_Debug
, // never shown to the user, disabled in release mode
75 wxLOG_Trace
, // trace messages are also only enabled in debug mode
76 wxLOG_Progress
, // used for progress indicator (not yet)
77 wxLOG_User
= 100, // user defined levels start here
81 // symbolic trace masks - wxLogTrace("foo", "some trace message...") will be
82 // discarded unless the string "foo" has been added to the list of allowed
83 // ones with AddTraceMask()
85 #define wxTRACE_MemAlloc wxT("memalloc") // trace memory allocation (new/delete)
86 #define wxTRACE_Messages wxT("messages") // trace window messages/X callbacks
87 #define wxTRACE_ResAlloc wxT("resalloc") // trace GDI resource allocation
88 #define wxTRACE_RefCount wxT("refcount") // trace various ref counting operations
91 #define wxTRACE_OleCalls wxT("ole") // OLE interface calls
94 // the trace masks have been superceded by symbolic trace constants, they're
95 // for compatibility only andwill be removed soon - do NOT use them
97 // meaning of different bits of the trace mask (which allows selectively
98 // enable/disable some trace messages)
99 #define wxTraceMemAlloc 0x0001 // trace memory allocation (new/delete)
100 #define wxTraceMessages 0x0002 // trace window messages/X callbacks
101 #define wxTraceResAlloc 0x0004 // trace GDI resource allocation
102 #define wxTraceRefCount 0x0008 // trace various ref counting operations
105 #define wxTraceOleCalls 0x0100 // OLE interface calls
108 #include "wx/iosfwrap.h"
110 // ----------------------------------------------------------------------------
111 // derive from this class to redirect (or suppress, or ...) log messages
112 // normally, only a single instance of this class exists but it's not enforced
113 // ----------------------------------------------------------------------------
115 class WXDLLIMPEXP_BASE wxLog
122 // Allow replacement of the fixed size static buffer with
123 // a user allocated one. Pass in NULL to restore the
124 // built in static buffer.
125 static wxChar
*SetLogBuffer( wxChar
*buf
, size_t size
= 0 );
127 // these functions allow to completely disable all log messages
128 // is logging disabled now?
129 static bool IsEnabled() { return ms_doLog
; }
130 // change the flag state, return the previous one
131 static bool EnableLogging(bool doIt
= TRUE
)
132 { bool doLogOld
= ms_doLog
; ms_doLog
= doIt
; return doLogOld
; }
134 // static sink function - see DoLog() for function to overload in the
136 static void OnLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
138 if ( IsEnabled() && ms_logLevel
>= level
) {
139 wxLog
*pLogger
= GetActiveTarget();
141 pLogger
->DoLog(level
, szString
, 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();
166 // change log target, pLogger may be NULL
167 static wxLog
*SetActiveTarget(wxLog
*pLogger
);
169 // suspend the message flushing of the main target until the next call
170 // to Resume() - this is mainly for internal use (to prevent wxYield()
171 // from flashing the messages)
172 static void Suspend() { ms_suspendCount
++; }
173 // must be called for each Suspend()!
174 static void Resume() { ms_suspendCount
--; }
176 // functions controlling the default wxLog behaviour
177 // verbose mode is activated by standard command-line '-verbose'
179 static void SetVerbose(bool bVerbose
= TRUE
) { ms_bVerbose
= bVerbose
; }
181 // Set log level. Log messages with level > logLevel will not be logged.
182 static void SetLogLevel(wxLogLevel logLevel
) { ms_logLevel
= logLevel
; }
184 // should GetActiveTarget() try to create a new log object if the
186 static void DontCreateOnDemand();
188 // trace mask (see wxTraceXXX constants for details)
189 static void SetTraceMask(wxTraceMask ulMask
) { ms_ulTraceMask
= ulMask
; }
190 // add string trace mask
191 static void AddTraceMask(const wxString
& str
)
192 { ms_aTraceMasks
.push_back(str
); }
193 // add string trace mask
194 static void RemoveTraceMask(const wxString
& str
);
195 // remove all string trace masks
196 static void ClearTraceMasks();
197 // get string trace masks
198 static const wxArrayString
&GetTraceMasks() { return ms_aTraceMasks
; }
200 // sets the timestamp string: this is used as strftime() format string
201 // for the log targets which add time stamps to the messages - set it
202 // to NULL to disable time stamping completely.
203 static void SetTimestamp(const wxChar
*ts
) { ms_timestamp
= ts
; }
207 // gets the verbose status
208 static bool GetVerbose() { return ms_bVerbose
; }
210 static wxTraceMask
GetTraceMask() { return ms_ulTraceMask
; }
211 // is this trace mask in the list?
212 static bool IsAllowedTraceMask(const wxChar
*mask
);
213 // return the current loglevel limit
214 static wxLogLevel
GetLogLevel() { return ms_logLevel
; }
216 // get the current timestamp format string (may be NULL)
217 static const wxChar
*GetTimestamp() { return ms_timestamp
; }
221 // put the time stamp into the string if ms_timestamp != NULL (don't
222 // change it otherwise)
223 static void TimeStamp(wxString
*str
);
225 // make dtor virtual for all derived classes
229 // this method exists for backwards compatibility only, don't use
230 bool HasPendingMessages() const { return TRUE
; }
233 // the logging functions that can be overriden
234 // default DoLog() prepends the time stamp and a prefix corresponding
235 // to the message to szString and then passes it to DoLogString()
236 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
237 // default DoLogString does nothing but is not pure virtual because if
238 // you override DoLog() you might not need it at all
239 virtual void DoLogString(const wxChar
*szString
, time_t t
);
245 static wxLog
*ms_pLogger
; // currently active log sink
246 static bool ms_doLog
; // FALSE => all logging disabled
247 static bool ms_bAutoCreate
; // create new log targets on demand?
248 static bool ms_bVerbose
; // FALSE => ignore LogInfo messages
250 static wxLogLevel ms_logLevel
; // limit logging to levels <= ms_logLevel
252 static size_t ms_suspendCount
; // if positive, logs are not flushed
254 // format string for strftime(), if NULL, time stamping log messages is
256 static const wxChar
*ms_timestamp
;
258 static wxTraceMask ms_ulTraceMask
; // controls wxLogTrace behaviour
259 static wxArrayString ms_aTraceMasks
; // more powerful filter for wxLogTrace
262 // ----------------------------------------------------------------------------
263 // "trivial" derivations of wxLog
264 // ----------------------------------------------------------------------------
266 // log everything to a "FILE *", stderr by default
267 class WXDLLIMPEXP_BASE wxLogStderr
: public wxLog
269 DECLARE_NO_COPY_CLASS(wxLogStderr
)
272 // redirect log output to a FILE
273 wxLogStderr(FILE *fp
= (FILE *) NULL
);
276 // implement sink function
277 virtual void DoLogString(const wxChar
*szString
, time_t t
);
282 #if wxUSE_STD_IOSTREAM
284 // log everything to an "ostream", cerr by default
285 class WXDLLIMPEXP_BASE wxLogStream
: public wxLog
288 // redirect log output to an ostream
289 wxLogStream(wxSTD ostream
*ostr
= (wxSTD ostream
*) NULL
);
292 // implement sink function
293 virtual void DoLogString(const wxChar
*szString
, time_t t
);
295 // using ptr here to avoid including <iostream.h> from this file
296 wxSTD ostream
*m_ostr
;
299 #endif // wxUSE_STD_IOSTREAM
301 // ----------------------------------------------------------------------------
302 // /dev/null log target: suppress logging until this object goes out of scope
303 // ----------------------------------------------------------------------------
311 // wxFile.Open() normally complains if file can't be opened, we don't
315 if ( !file.Open("bar") )
316 ... process error ourselves ...
318 // ~wxLogNull called, old log sink restored
321 class WXDLLIMPEXP_BASE wxLogNull
324 wxLogNull() : m_flagOld(wxLog::EnableLogging(FALSE
)) { }
325 ~wxLogNull() { (void)wxLog::EnableLogging(m_flagOld
); }
328 bool m_flagOld
; // the previous value of the wxLog::ms_doLog
331 // ----------------------------------------------------------------------------
332 // chaining log target: installs itself as a log target and passes all
333 // messages to the real log target given to it in the ctor but also forwards
334 // them to the previously active one
336 // note that you don't have to call SetActiveTarget() with this class, it
337 // does it itself in its ctor
338 // ----------------------------------------------------------------------------
340 class WXDLLIMPEXP_BASE wxLogChain
: public wxLog
343 wxLogChain(wxLog
*logger
);
344 virtual ~wxLogChain();
346 // change the new log target
347 void SetLog(wxLog
*logger
);
349 // this can be used to temporarily disable (and then reenable) passing
350 // messages to the old logger (by default we do pass them)
351 void PassMessages(bool bDoPass
) { m_bPassMessages
= bDoPass
; }
353 // are we passing the messages to the previous log target?
354 bool IsPassingMessages() const { return m_bPassMessages
; }
356 // return the previous log target (may be NULL)
357 wxLog
*GetOldLog() const { return m_logOld
; }
359 // override base class version to flush the old logger as well
360 virtual void Flush();
363 // pass the chain to the old logger if needed
364 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
367 // the current log target
370 // the previous log target
373 // do we pass the messages to the old logger?
374 bool m_bPassMessages
;
376 DECLARE_NO_COPY_CLASS(wxLogChain
)
379 // a chain log target which uses itself as the new logger
380 class WXDLLIMPEXP_BASE wxLogPassThrough
: public wxLogChain
386 DECLARE_NO_COPY_CLASS(wxLogPassThrough
)
390 // include GUI log targets:
391 #include "wx/generic/logg.h"
394 // ============================================================================
396 // ============================================================================
398 // ----------------------------------------------------------------------------
399 // Log functions should be used by application instead of stdio, iostream &c
400 // for log messages for easy redirection
401 // ----------------------------------------------------------------------------
403 // ----------------------------------------------------------------------------
404 // get error code/error message from system in a portable way
405 // ----------------------------------------------------------------------------
407 // return the last system error code
408 WXDLLIMPEXP_BASE
unsigned long wxSysErrorCode();
410 // return the error message for given (or last if 0) error code
411 WXDLLIMPEXP_BASE
const wxChar
* wxSysErrorMsg(unsigned long nErrCode
= 0);
413 // ----------------------------------------------------------------------------
414 // define wxLog<level>
415 // ----------------------------------------------------------------------------
417 #define DECLARE_LOG_FUNCTION(level) \
418 extern void WXDLLIMPEXP_BASE wxVLog##level(const wxChar *szFormat, \
420 extern void WXDLLIMPEXP_BASE wxLog##level(const wxChar *szFormat, \
421 ...) ATTRIBUTE_PRINTF_1
422 #define DECLARE_LOG_FUNCTION2_EXP(level, arg, expdecl) \
423 extern void expdecl wxVLog##level(arg, const wxChar *szFormat, \
425 extern void expdecl wxLog##level(arg, const wxChar *szFormat, \
426 ...) ATTRIBUTE_PRINTF_2
427 #define DECLARE_LOG_FUNCTION2(level, arg) \
428 DECLARE_LOG_FUNCTION2_EXP(level, arg, WXDLLIMPEXP_BASE)
432 // log functions do nothing at all
433 #define DECLARE_LOG_FUNCTION(level) \
434 inline void wxVLog##level(const wxChar *szFormat, \
435 va_list argptr) { } \
436 inline void wxLog##level(const wxChar *szFormat, ...) { }
437 #define DECLARE_LOG_FUNCTION2(level, arg) \
438 inline void wxVLog##level(arg, const wxChar *szFormat, \
440 inline void wxLog##level(arg, const wxChar *szFormat, ...) { }
442 // Empty Class to fake wxLogNull
443 class WXDLLIMPEXP_BASE wxLogNull
449 // Dummy macros to replace some functions.
450 #define wxSysErrorCode() (unsigned long)0
451 #define wxSysErrorMsg( X ) (const wxChar*)NULL
453 // Fake symbolic trace masks... for those that are used frequently
454 #define wxTRACE_OleCalls wxEmptyString // OLE interface calls
456 #endif // wxUSE_LOG/!wxUSE_LOG
458 // a generic function for all levels (level is passes as parameter)
459 DECLARE_LOG_FUNCTION2(Generic
, wxLogLevel level
);
461 // one function per each level
462 DECLARE_LOG_FUNCTION(FatalError
);
463 DECLARE_LOG_FUNCTION(Error
);
464 DECLARE_LOG_FUNCTION(Warning
);
465 DECLARE_LOG_FUNCTION(Message
);
466 DECLARE_LOG_FUNCTION(Info
);
467 DECLARE_LOG_FUNCTION(Verbose
);
469 // this function sends the log message to the status line of the top level
470 // application frame, if any
471 DECLARE_LOG_FUNCTION(Status
);
474 // this one is the same as previous except that it allows to explicitly
475 // specify the frame to which the output should go
476 DECLARE_LOG_FUNCTION2_EXP(Status
, wxFrame
*pFrame
, WXDLLIMPEXP_CORE
);
479 // additional one: as wxLogError, but also logs last system call error code
480 // and the corresponding error message if available
481 DECLARE_LOG_FUNCTION(SysError
);
483 // and another one which also takes the error code (for those broken APIs
484 // that don't set the errno (like registry APIs in Win32))
485 DECLARE_LOG_FUNCTION2(SysError
, long lErrCode
);
487 // debug functions do nothing in release mode
489 DECLARE_LOG_FUNCTION(Debug
);
491 // first kind of LogTrace is unconditional: it doesn't check the level,
492 DECLARE_LOG_FUNCTION(Trace
);
494 // this second version will only log the message if the mask had been
495 // added to the list of masks with AddTraceMask()
496 DECLARE_LOG_FUNCTION2(Trace
, const wxChar
*mask
);
498 // the last one does nothing if all of level bits are not set
499 // in wxLog::GetActive()->GetTraceMask() - it's deprecated in favour of
500 // string identifiers
501 DECLARE_LOG_FUNCTION2(Trace
, wxTraceMask mask
);
503 // these functions do nothing in release builds
504 inline void wxVLogDebug(const wxChar
*, va_list) { }
505 inline void wxLogDebug(const wxChar
*, ...) { }
506 inline void wxVLogTrace(const wxChar
*, va_list) { }
507 inline void wxLogTrace(const wxChar
*, ...) { }
508 inline void wxVLogTrace(wxTraceMask
, const wxChar
*, va_list) { }
509 inline void wxLogTrace(wxTraceMask
, const wxChar
*, ...) { }
510 inline void wxVLogTrace(const wxChar
*, const wxChar
*, va_list) { }
511 inline void wxLogTrace(const wxChar
*, const wxChar
*, ...) { }
512 #endif // debug/!debug
514 // wxLogFatalError helper: show the (fatal) error to the user in a safe way,
515 // i.e. without using wxMessageBox() for example because it could crash
516 void WXDLLIMPEXP_BASE
517 wxSafeShowMessage(const wxString
& title
, const wxString
& text
);
519 // ----------------------------------------------------------------------------
520 // debug only logging functions: use them with API name and error code
521 // ----------------------------------------------------------------------------
524 // make life easier for people using VC++ IDE: clicking on the message
525 // will take us immediately to the place of the failed API
527 #define wxLogApiError(api, rc) \
528 wxLogDebug(wxT("%s(%d): '%s' failed with error 0x%08lx (%s)."), \
529 __TFILE__, __LINE__, api, \
530 (long)rc, wxSysErrorMsg(rc))
532 #define wxLogApiError(api, rc) \
533 wxLogDebug(wxT("In file %s at line %d: '%s' failed with ") \
534 wxT("error 0x%08lx (%s)."), \
535 __TFILE__, __LINE__, api, \
536 (long)rc, wxSysErrorMsg(rc))
539 #define wxLogLastError(api) wxLogApiError(api, wxSysErrorCode())
542 inline void wxLogApiError(const wxChar
*, long) { }
543 inline void wxLogLastError(const wxChar
*) { }
544 #endif //debug/!debug