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
123 // Allow replacement of the fixed size static buffer with
124 // a user allocated one. Pass in NULL to restore the
125 // built in static buffer.
126 static wxChar
*SetLogBuffer( wxChar
*buf
, size_t size
= 0 );
128 // these functions allow to completely disable all log messages
130 // is logging disabled now?
131 static bool IsEnabled() { return ms_doLog
; }
133 // change the flag state, return the previous one
134 static bool EnableLogging(bool doIt
= true)
135 { bool doLogOld
= ms_doLog
; ms_doLog
= doIt
; return doLogOld
; }
137 // static sink function - see DoLog() for function to overload in the
139 static void OnLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
141 if ( IsEnabled() && ms_logLevel
>= level
)
143 wxLog
*pLogger
= GetActiveTarget();
145 pLogger
->DoLog(level
, szString
, t
);
151 // flush shows all messages if they're not logged immediately (FILE
152 // and iostream logs don't need it, but wxGuiLog does to avoid showing
153 // 17 modal dialogs one after another)
154 virtual void Flush();
156 // flush the active target if any
157 static void FlushActive()
159 if ( !ms_suspendCount
)
161 wxLog
*log
= GetActiveTarget();
167 // only one sink is active at each moment
168 // get current log target, will call wxApp::CreateLogTarget() to
169 // create one if none exists
170 static wxLog
*GetActiveTarget();
172 // change log target, pLogger may be NULL
173 static wxLog
*SetActiveTarget(wxLog
*pLogger
);
175 // suspend the message flushing of the main target until the next call
176 // to Resume() - this is mainly for internal use (to prevent wxYield()
177 // from flashing the messages)
178 static void Suspend() { ms_suspendCount
++; }
180 // must be called for each Suspend()!
181 static void Resume() { ms_suspendCount
--; }
183 // functions controlling the default wxLog behaviour
184 // verbose mode is activated by standard command-line '-verbose'
186 static void SetVerbose(bool bVerbose
= true) { ms_bVerbose
= bVerbose
; }
188 // Set log level. Log messages with level > logLevel will not be logged.
189 static void SetLogLevel(wxLogLevel logLevel
) { ms_logLevel
= logLevel
; }
191 // should GetActiveTarget() try to create a new log object if the
193 static void DontCreateOnDemand();
195 // trace mask (see wxTraceXXX constants for details)
196 static void SetTraceMask(wxTraceMask ulMask
) { ms_ulTraceMask
= ulMask
; }
198 // add string trace mask
199 static void AddTraceMask(const wxString
& str
)
200 { ms_aTraceMasks
.push_back(str
); }
202 // add string trace mask
203 static void RemoveTraceMask(const wxString
& str
);
205 // remove all string trace masks
206 static void ClearTraceMasks();
208 // get string trace masks
209 static const wxArrayString
&GetTraceMasks() { return ms_aTraceMasks
; }
211 // sets the timestamp string: this is used as strftime() format string
212 // for the log targets which add time stamps to the messages - set it
213 // to NULL to disable time stamping completely.
214 static void SetTimestamp(const wxChar
*ts
) { ms_timestamp
= ts
; }
219 // gets the verbose status
220 static bool GetVerbose() { return ms_bVerbose
; }
223 static wxTraceMask
GetTraceMask() { return ms_ulTraceMask
; }
225 // is this trace mask in the list?
226 static bool IsAllowedTraceMask(const wxChar
*mask
);
228 // return the current loglevel limit
229 static wxLogLevel
GetLogLevel() { return ms_logLevel
; }
231 // get the current timestamp format string (may be NULL)
232 static const wxChar
*GetTimestamp() { return ms_timestamp
; }
237 // put the time stamp into the string if ms_timestamp != NULL (don't
238 // change it otherwise)
239 static void TimeStamp(wxString
*str
);
241 // make dtor virtual for all derived classes
245 // this method exists for backwards compatibility only, don't use
246 bool HasPendingMessages() const { return true; }
249 // the logging functions that can be overriden
251 // default DoLog() prepends the time stamp and a prefix corresponding
252 // to the message to szString and then passes it to DoLogString()
253 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
255 // default DoLogString does nothing but is not pure virtual because if
256 // you override DoLog() you might not need it at all
257 virtual void DoLogString(const wxChar
*szString
, time_t t
);
263 static wxLog
*ms_pLogger
; // currently active log sink
264 static bool ms_doLog
; // false => all logging disabled
265 static bool ms_bAutoCreate
; // create new log targets on demand?
266 static bool ms_bVerbose
; // false => ignore LogInfo messages
268 static wxLogLevel ms_logLevel
; // limit logging to levels <= ms_logLevel
270 static size_t ms_suspendCount
; // if positive, logs are not flushed
272 // format string for strftime(), if NULL, time stamping log messages is
274 static const wxChar
*ms_timestamp
;
276 static wxTraceMask ms_ulTraceMask
; // controls wxLogTrace behaviour
277 static wxArrayString ms_aTraceMasks
; // more powerful filter for wxLogTrace
280 // ----------------------------------------------------------------------------
281 // "trivial" derivations of wxLog
282 // ----------------------------------------------------------------------------
284 // log everything to a "FILE *", stderr by default
285 class WXDLLIMPEXP_BASE wxLogStderr
: public wxLog
287 DECLARE_NO_COPY_CLASS(wxLogStderr
)
290 // redirect log output to a FILE
291 wxLogStderr(FILE *fp
= (FILE *) NULL
);
294 // implement sink function
295 virtual void DoLogString(const wxChar
*szString
, time_t t
);
300 #if wxUSE_STD_IOSTREAM
302 // log everything to an "ostream", cerr by default
303 class WXDLLIMPEXP_BASE wxLogStream
: public wxLog
306 // redirect log output to an ostream
307 wxLogStream(wxSTD ostream
*ostr
= (wxSTD ostream
*) NULL
);
310 // implement sink function
311 virtual void DoLogString(const wxChar
*szString
, time_t t
);
313 // using ptr here to avoid including <iostream.h> from this file
314 wxSTD ostream
*m_ostr
;
317 #endif // wxUSE_STD_IOSTREAM
319 // ----------------------------------------------------------------------------
320 // /dev/null log target: suppress logging until this object goes out of scope
321 // ----------------------------------------------------------------------------
329 // wxFile.Open() normally complains if file can't be opened, we don't
333 if ( !file.Open("bar") )
334 ... process error ourselves ...
336 // ~wxLogNull called, old log sink restored
339 class WXDLLIMPEXP_BASE wxLogNull
342 wxLogNull() : m_flagOld(wxLog::EnableLogging(false)) { }
343 ~wxLogNull() { (void)wxLog::EnableLogging(m_flagOld
); }
346 bool m_flagOld
; // the previous value of the wxLog::ms_doLog
349 // ----------------------------------------------------------------------------
350 // chaining log target: installs itself as a log target and passes all
351 // messages to the real log target given to it in the ctor but also forwards
352 // them to the previously active one
354 // note that you don't have to call SetActiveTarget() with this class, it
355 // does it itself in its ctor
356 // ----------------------------------------------------------------------------
358 class WXDLLIMPEXP_BASE wxLogChain
: public wxLog
361 wxLogChain(wxLog
*logger
);
362 virtual ~wxLogChain();
364 // change the new log target
365 void SetLog(wxLog
*logger
);
367 // this can be used to temporarily disable (and then reenable) passing
368 // messages to the old logger (by default we do pass them)
369 void PassMessages(bool bDoPass
) { m_bPassMessages
= bDoPass
; }
371 // are we passing the messages to the previous log target?
372 bool IsPassingMessages() const { return m_bPassMessages
; }
374 // return the previous log target (may be NULL)
375 wxLog
*GetOldLog() const { return m_logOld
; }
377 // override base class version to flush the old logger as well
378 virtual void Flush();
381 // pass the chain to the old logger if needed
382 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
385 // the current log target
388 // the previous log target
391 // do we pass the messages to the old logger?
392 bool m_bPassMessages
;
394 DECLARE_NO_COPY_CLASS(wxLogChain
)
397 // a chain log target which uses itself as the new logger
398 class WXDLLIMPEXP_BASE wxLogPassThrough
: public wxLogChain
404 DECLARE_NO_COPY_CLASS(wxLogPassThrough
)
408 // include GUI log targets:
409 #include "wx/generic/logg.h"
412 // ============================================================================
414 // ============================================================================
416 // ----------------------------------------------------------------------------
417 // Log functions should be used by application instead of stdio, iostream &c
418 // for log messages for easy redirection
419 // ----------------------------------------------------------------------------
421 // ----------------------------------------------------------------------------
422 // get error code/error message from system in a portable way
423 // ----------------------------------------------------------------------------
425 // return the last system error code
426 WXDLLIMPEXP_BASE
unsigned long wxSysErrorCode();
428 // return the error message for given (or last if 0) error code
429 WXDLLIMPEXP_BASE
const wxChar
* wxSysErrorMsg(unsigned long nErrCode
= 0);
431 // ----------------------------------------------------------------------------
432 // define wxLog<level>
433 // ----------------------------------------------------------------------------
435 #define DECLARE_LOG_FUNCTION(level) \
436 extern void WXDLLIMPEXP_BASE wxVLog##level(const wxChar *szFormat, \
438 extern void WXDLLIMPEXP_BASE wxLog##level(const wxChar *szFormat, \
439 ...) ATTRIBUTE_PRINTF_1
440 #define DECLARE_LOG_FUNCTION2_EXP(level, arg, expdecl) \
441 extern void expdecl wxVLog##level(arg, const wxChar *szFormat, \
443 extern void expdecl wxLog##level(arg, const wxChar *szFormat, \
444 ...) ATTRIBUTE_PRINTF_2
445 #define DECLARE_LOG_FUNCTION2(level, arg) \
446 DECLARE_LOG_FUNCTION2_EXP(level, arg, WXDLLIMPEXP_BASE)
450 // log functions do nothing at all
451 #define DECLARE_LOG_FUNCTION(level) \
452 inline void wxVLog##level(const wxChar *szFormat, \
453 va_list argptr) { } \
454 inline void wxLog##level(const wxChar *szFormat, ...) { }
455 #define DECLARE_LOG_FUNCTION2(level, arg) \
456 inline void wxVLog##level(arg, const wxChar *szFormat, \
458 inline void wxLog##level(arg, const wxChar *szFormat, ...) { }
460 // Empty Class to fake wxLogNull
461 class WXDLLIMPEXP_BASE wxLogNull
467 // Dummy macros to replace some functions.
468 #define wxSysErrorCode() (unsigned long)0
469 #define wxSysErrorMsg( X ) (const wxChar*)NULL
471 // Fake symbolic trace masks... for those that are used frequently
472 #define wxTRACE_OleCalls wxEmptyString // OLE interface calls
474 #endif // wxUSE_LOG/!wxUSE_LOG
476 // a generic function for all levels (level is passes as parameter)
477 DECLARE_LOG_FUNCTION2(Generic
, wxLogLevel level
);
479 // one function per each level
480 DECLARE_LOG_FUNCTION(FatalError
);
481 DECLARE_LOG_FUNCTION(Error
);
482 DECLARE_LOG_FUNCTION(Warning
);
483 DECLARE_LOG_FUNCTION(Message
);
484 DECLARE_LOG_FUNCTION(Info
);
485 DECLARE_LOG_FUNCTION(Verbose
);
487 // this function sends the log message to the status line of the top level
488 // application frame, if any
489 DECLARE_LOG_FUNCTION(Status
);
492 // this one is the same as previous except that it allows to explicitly
493 // specify the frame to which the output should go
494 DECLARE_LOG_FUNCTION2_EXP(Status
, wxFrame
*pFrame
, WXDLLIMPEXP_CORE
);
497 // additional one: as wxLogError, but also logs last system call error code
498 // and the corresponding error message if available
499 DECLARE_LOG_FUNCTION(SysError
);
501 // and another one which also takes the error code (for those broken APIs
502 // that don't set the errno (like registry APIs in Win32))
503 DECLARE_LOG_FUNCTION2(SysError
, long lErrCode
);
505 // debug functions do nothing in release mode
507 DECLARE_LOG_FUNCTION(Debug
);
509 // there is no more unconditional LogTrace: it is not different from
510 // LogDebug and it creates overload ambiguities
511 //DECLARE_LOG_FUNCTION(Trace);
513 // this version only logs the message if the mask had been added to the
514 // list of masks with AddTraceMask()
515 DECLARE_LOG_FUNCTION2(Trace
, const wxChar
*mask
);
517 // and this one does nothing if all of level bits are not set in
518 // wxLog::GetActive()->GetTraceMask() -- it's deprecated in favour of
519 // string identifiers
520 DECLARE_LOG_FUNCTION2(Trace
, wxTraceMask mask
);
522 // these functions do nothing in release builds
523 inline void wxVLogDebug(const wxChar
*, va_list) { }
524 inline void wxLogDebug(const wxChar
*, ...) { }
525 inline void wxVLogTrace(wxTraceMask
, const wxChar
*, va_list) { }
526 inline void wxLogTrace(wxTraceMask
, const wxChar
*, ...) { }
527 inline void wxVLogTrace(const wxChar
*, const wxChar
*, va_list) { }
528 inline void wxLogTrace(const wxChar
*, const wxChar
*, ...) { }
529 #endif // debug/!debug
531 // wxLogFatalError helper: show the (fatal) error to the user in a safe way,
532 // i.e. without using wxMessageBox() for example because it could crash
533 void WXDLLIMPEXP_BASE
534 wxSafeShowMessage(const wxString
& title
, const wxString
& text
);
536 // ----------------------------------------------------------------------------
537 // debug only logging functions: use them with API name and error code
538 // ----------------------------------------------------------------------------
541 // make life easier for people using VC++ IDE: clicking on the message
542 // will take us immediately to the place of the failed API
544 #define wxLogApiError(api, rc) \
545 wxLogDebug(wxT("%s(%d): '%s' failed with error 0x%08lx (%s)."), \
546 __TFILE__, __LINE__, api, \
547 (long)rc, wxSysErrorMsg(rc))
549 #define wxLogApiError(api, rc) \
550 wxLogDebug(wxT("In file %s at line %d: '%s' failed with ") \
551 wxT("error 0x%08lx (%s)."), \
552 __TFILE__, __LINE__, api, \
553 (long)rc, wxSysErrorMsg(rc))
556 #define wxLogLastError(api) wxLogApiError(api, wxSysErrorCode())
559 inline void wxLogApiError(const wxChar
*, long) { }
560 inline void wxLogLastError(const wxChar
*) { }
561 #endif //debug/!debug