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(__APPLE__)
16 #pragma interface "log.h"
19 #include "wx/string.h"
23 // ----------------------------------------------------------------------------
24 // forward declarations
25 // ----------------------------------------------------------------------------
28 class WXDLLIMPEXP_CORE wxTextCtrl
;
29 class WXDLLIMPEXP_CORE wxLogFrame
;
30 class WXDLLIMPEXP_CORE wxFrame
;
33 // ----------------------------------------------------------------------------
35 // ----------------------------------------------------------------------------
37 typedef unsigned long wxTraceMask
;
38 typedef unsigned long wxLogLevel
;
40 // ----------------------------------------------------------------------------
42 // ----------------------------------------------------------------------------
45 #include <time.h> // for time_t
48 #include "wx/dynarray.h"
50 #ifndef wxUSE_LOG_DEBUG
52 # define wxUSE_LOG_DEBUG 1
53 # else // !__WXDEBUG__
54 # define wxUSE_LOG_DEBUG 0
58 // ----------------------------------------------------------------------------
60 // ----------------------------------------------------------------------------
62 // different standard log levels (you may also define your own)
65 wxLOG_FatalError
, // program can't continue, abort immediately
66 wxLOG_Error
, // a serious error, user must be informed about it
67 wxLOG_Warning
, // user is normally informed about it but may be ignored
68 wxLOG_Message
, // normal message (i.e. normal output of a non GUI app)
69 wxLOG_Status
, // informational: might go to the status line of GUI app
70 wxLOG_Info
, // informational message (a.k.a. 'Verbose')
71 wxLOG_Debug
, // never shown to the user, disabled in release mode
72 wxLOG_Trace
, // trace messages are also only enabled in debug mode
73 wxLOG_Progress
, // used for progress indicator (not yet)
74 wxLOG_User
= 100, // user defined levels start here
78 // symbolic trace masks - wxLogTrace("foo", "some trace message...") will be
79 // discarded unless the string "foo" has been added to the list of allowed
80 // ones with AddTraceMask()
82 #define wxTRACE_MemAlloc wxT("memalloc") // trace memory allocation (new/delete)
83 #define wxTRACE_Messages wxT("messages") // trace window messages/X callbacks
84 #define wxTRACE_ResAlloc wxT("resalloc") // trace GDI resource allocation
85 #define wxTRACE_RefCount wxT("refcount") // trace various ref counting operations
88 #define wxTRACE_OleCalls wxT("ole") // OLE interface calls
91 // the trace masks have been superceded by symbolic trace constants, they're
92 // for compatibility only andwill be removed soon - do NOT use them
94 // meaning of different bits of the trace mask (which allows selectively
95 // enable/disable some trace messages)
96 #define wxTraceMemAlloc 0x0001 // trace memory allocation (new/delete)
97 #define wxTraceMessages 0x0002 // trace window messages/X callbacks
98 #define wxTraceResAlloc 0x0004 // trace GDI resource allocation
99 #define wxTraceRefCount 0x0008 // trace various ref counting operations
102 #define wxTraceOleCalls 0x0100 // OLE interface calls
105 #include "wx/iosfwrap.h"
107 // ----------------------------------------------------------------------------
108 // derive from this class to redirect (or suppress, or ...) log messages
109 // normally, only a single instance of this class exists but it's not enforced
110 // ----------------------------------------------------------------------------
112 class WXDLLIMPEXP_BASE wxLog
119 // Allow replacement of the fixed size static buffer with
120 // a user allocated one. Pass in NULL to restore the
121 // built in static buffer.
122 static wxChar
*SetLogBuffer( wxChar
*buf
, size_t size
= 0 );
124 // these functions allow to completely disable all log messages
125 // is logging disabled now?
126 static bool IsEnabled() { return ms_doLog
; }
127 // change the flag state, return the previous one
128 static bool EnableLogging(bool doIt
= TRUE
)
129 { bool doLogOld
= ms_doLog
; ms_doLog
= doIt
; return doLogOld
; }
131 // static sink function - see DoLog() for function to overload in the
133 static void OnLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
135 if ( IsEnabled() && ms_logLevel
>= level
) {
136 wxLog
*pLogger
= GetActiveTarget();
138 pLogger
->DoLog(level
, szString
, t
);
143 // flush shows all messages if they're not logged immediately (FILE
144 // and iostream logs don't need it, but wxGuiLog does to avoid showing
145 // 17 modal dialogs one after another)
146 virtual void Flush();
148 // flush the active target if any
149 static void FlushActive()
151 if ( !ms_suspendCount
)
153 wxLog
*log
= GetActiveTarget();
159 // only one sink is active at each moment
160 // get current log target, will call wxApp::CreateLogTarget() to
161 // create one if none exists
162 static wxLog
*GetActiveTarget();
163 // change log target, pLogger may be NULL
164 static wxLog
*SetActiveTarget(wxLog
*pLogger
);
166 // suspend the message flushing of the main target until the next call
167 // to Resume() - this is mainly for internal use (to prevent wxYield()
168 // from flashing the messages)
169 static void Suspend() { ms_suspendCount
++; }
170 // must be called for each Suspend()!
171 static void Resume() { ms_suspendCount
--; }
173 // functions controlling the default wxLog behaviour
174 // verbose mode is activated by standard command-line '-verbose'
176 static void SetVerbose(bool bVerbose
= TRUE
) { ms_bVerbose
= bVerbose
; }
178 // Set log level. Log messages with level > logLevel will not be logged.
179 static void SetLogLevel(wxLogLevel logLevel
) { ms_logLevel
= logLevel
; }
181 // should GetActiveTarget() try to create a new log object if the
183 static void DontCreateOnDemand();
185 // trace mask (see wxTraceXXX constants for details)
186 static void SetTraceMask(wxTraceMask ulMask
) { ms_ulTraceMask
= ulMask
; }
187 // add string trace mask
188 static void AddTraceMask(const wxString
& str
) { ms_aTraceMasks
.Add(str
); }
189 // add string trace mask
190 static void RemoveTraceMask(const wxString
& str
);
191 // remove all string trace masks
192 static void ClearTraceMasks();
193 // get string trace masks
194 static const wxArrayString
&GetTraceMasks() { return ms_aTraceMasks
; }
196 // sets the timestamp string: this is used as strftime() format string
197 // for the log targets which add time stamps to the messages - set it
198 // to NULL to disable time stamping completely.
199 static void SetTimestamp(const wxChar
*ts
) { ms_timestamp
= ts
; }
203 // gets the verbose status
204 static bool GetVerbose() { return ms_bVerbose
; }
206 static wxTraceMask
GetTraceMask() { return ms_ulTraceMask
; }
207 // is this trace mask in the list?
208 static bool IsAllowedTraceMask(const wxChar
*mask
)
209 { return ms_aTraceMasks
.Index(mask
) != wxNOT_FOUND
; }
210 // return the current loglevel limit
211 static wxLogLevel
GetLogLevel() { return ms_logLevel
; }
213 // get the current timestamp format string (may be NULL)
214 static const wxChar
*GetTimestamp() { return ms_timestamp
; }
218 // put the time stamp into the string if ms_timestamp != NULL (don't
219 // change it otherwise)
220 static void TimeStamp(wxString
*str
);
222 // make dtor virtual for all derived classes
226 // this method exists for backwards compatibility only, don't use
227 bool HasPendingMessages() const { return TRUE
; }
230 // the logging functions that can be overriden
231 // default DoLog() prepends the time stamp and a prefix corresponding
232 // to the message to szString and then passes it to DoLogString()
233 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
234 // default DoLogString does nothing but is not pure virtual because if
235 // you override DoLog() you might not need it at all
236 virtual void DoLogString(const wxChar
*szString
, time_t t
);
242 static wxLog
*ms_pLogger
; // currently active log sink
243 static bool ms_doLog
; // FALSE => all logging disabled
244 static bool ms_bAutoCreate
; // create new log targets on demand?
245 static bool ms_bVerbose
; // FALSE => ignore LogInfo messages
247 static wxLogLevel ms_logLevel
; // limit logging to levels <= ms_logLevel
249 static size_t ms_suspendCount
; // if positive, logs are not flushed
251 // format string for strftime(), if NULL, time stamping log messages is
253 static const wxChar
*ms_timestamp
;
255 static wxTraceMask ms_ulTraceMask
; // controls wxLogTrace behaviour
256 static wxArrayString ms_aTraceMasks
; // more powerful filter for wxLogTrace
259 // ----------------------------------------------------------------------------
260 // "trivial" derivations of wxLog
261 // ----------------------------------------------------------------------------
263 // log everything to a "FILE *", stderr by default
264 class WXDLLIMPEXP_BASE wxLogStderr
: public wxLog
266 DECLARE_NO_COPY_CLASS(wxLogStderr
)
269 // redirect log output to a FILE
270 wxLogStderr(FILE *fp
= (FILE *) NULL
);
273 // implement sink function
274 virtual void DoLogString(const wxChar
*szString
, time_t t
);
279 #if wxUSE_STD_IOSTREAM
281 // log everything to an "ostream", cerr by default
282 class WXDLLIMPEXP_BASE wxLogStream
: public wxLog
285 // redirect log output to an ostream
286 wxLogStream(wxSTD ostream
*ostr
= (wxSTD ostream
*) NULL
);
289 // implement sink function
290 virtual void DoLogString(const wxChar
*szString
, time_t t
);
292 // using ptr here to avoid including <iostream.h> from this file
293 wxSTD ostream
*m_ostr
;
296 #endif // wxUSE_STD_IOSTREAM
298 // ----------------------------------------------------------------------------
299 // /dev/null log target: suppress logging until this object goes out of scope
300 // ----------------------------------------------------------------------------
308 // wxFile.Open() normally complains if file can't be opened, we don't
312 if ( !file.Open("bar") )
313 ... process error ourselves ...
315 // ~wxLogNull called, old log sink restored
318 class WXDLLIMPEXP_BASE wxLogNull
321 wxLogNull() : m_flagOld(wxLog::EnableLogging(FALSE
)) { }
322 ~wxLogNull() { (void)wxLog::EnableLogging(m_flagOld
); }
325 bool m_flagOld
; // the previous value of the wxLog::ms_doLog
328 // ----------------------------------------------------------------------------
329 // chaining log target: installs itself as a log target and passes all
330 // messages to the real log target given to it in the ctor but also forwards
331 // them to the previously active one
333 // note that you don't have to call SetActiveTarget() with this class, it
334 // does it itself in its ctor
335 // ----------------------------------------------------------------------------
337 class WXDLLIMPEXP_BASE wxLogChain
: public wxLog
340 wxLogChain(wxLog
*logger
);
341 virtual ~wxLogChain();
343 // change the new log target
344 void SetLog(wxLog
*logger
);
346 // this can be used to temporarily disable (and then reenable) passing
347 // messages to the old logger (by default we do pass them)
348 void PassMessages(bool bDoPass
) { m_bPassMessages
= bDoPass
; }
350 // are we passing the messages to the previous log target?
351 bool IsPassingMessages() const { return m_bPassMessages
; }
353 // return the previous log target (may be NULL)
354 wxLog
*GetOldLog() const { return m_logOld
; }
356 // override base class version to flush the old logger as well
357 virtual void Flush();
360 // pass the chain to the old logger if needed
361 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
364 // the current log target
367 // the previous log target
370 // do we pass the messages to the old logger?
371 bool m_bPassMessages
;
373 DECLARE_NO_COPY_CLASS(wxLogChain
)
376 // a chain log target which uses itself as the new logger
377 class WXDLLIMPEXP_BASE wxLogPassThrough
: public wxLogChain
384 // include GUI log targets:
385 #include "wx/generic/logg.h"
388 // ============================================================================
390 // ============================================================================
392 // ----------------------------------------------------------------------------
393 // Log functions should be used by application instead of stdio, iostream &c
394 // for log messages for easy redirection
395 // ----------------------------------------------------------------------------
397 // ----------------------------------------------------------------------------
398 // get error code/error message from system in a portable way
399 // ----------------------------------------------------------------------------
401 // return the last system error code
402 WXDLLIMPEXP_BASE
unsigned long wxSysErrorCode();
404 // return the error message for given (or last if 0) error code
405 WXDLLIMPEXP_BASE
const wxChar
* wxSysErrorMsg(unsigned long nErrCode
= 0);
407 // ----------------------------------------------------------------------------
408 // define wxLog<level>
409 // ----------------------------------------------------------------------------
411 #define DECLARE_LOG_FUNCTION(level) \
412 extern void WXDLLIMPEXP_BASE wxVLog##level(const wxChar *szFormat, \
414 extern void WXDLLIMPEXP_BASE wxLog##level(const wxChar *szFormat, \
415 ...) ATTRIBUTE_PRINTF_1
416 #define DECLARE_LOG_FUNCTION2_EXP(level, arg, expdecl) \
417 extern void expdecl wxVLog##level(arg, const wxChar *szFormat, \
419 extern void expdecl wxLog##level(arg, const wxChar *szFormat, \
420 ...) ATTRIBUTE_PRINTF_2
421 #define DECLARE_LOG_FUNCTION2(level, arg) \
422 DECLARE_LOG_FUNCTION2_EXP(level, arg, WXDLLIMPEXP_BASE)
426 // log functions do nothing at all
427 #define DECLARE_LOG_FUNCTION(level) \
428 inline void wxVLog##level(const wxChar *szFormat, \
429 va_list argptr) { } \
430 inline void wxLog##level(const wxChar *szFormat, ...) { }
431 #define DECLARE_LOG_FUNCTION2(level, arg) \
432 inline void wxVLog##level(arg, const wxChar *szFormat, \
434 inline void wxLog##level(arg, const wxChar *szFormat, ...) { }
436 // Empty Class to fake wxLogNull
437 class WXDLLIMPEXP_BASE wxLogNull
443 // Dummy macros to replace some functions.
444 #define wxSysErrorCode() (unsigned long)0
445 #define wxSysErrorMsg( X ) (const wxChar*)NULL
447 // Fake symbolic trace masks... for those that are used frequently
448 #define wxTRACE_OleCalls wxT("") // OLE interface calls
450 #endif // wxUSE_LOG/!wxUSE_LOG
452 // a generic function for all levels (level is passes as parameter)
453 DECLARE_LOG_FUNCTION2(Generic
, wxLogLevel level
);
455 // one function per each level
456 DECLARE_LOG_FUNCTION(FatalError
);
457 DECLARE_LOG_FUNCTION(Error
);
458 DECLARE_LOG_FUNCTION(Warning
);
459 DECLARE_LOG_FUNCTION(Message
);
460 DECLARE_LOG_FUNCTION(Info
);
461 DECLARE_LOG_FUNCTION(Verbose
);
463 // this function sends the log message to the status line of the top level
464 // application frame, if any
465 DECLARE_LOG_FUNCTION(Status
);
468 // this one is the same as previous except that it allows to explicitly
469 // specify the frame to which the output should go
470 DECLARE_LOG_FUNCTION2_EXP(Status
, wxFrame
*pFrame
, WXDLLIMPEXP_CORE
);
473 // additional one: as wxLogError, but also logs last system call error code
474 // and the corresponding error message if available
475 DECLARE_LOG_FUNCTION(SysError
);
477 // and another one which also takes the error code (for those broken APIs
478 // that don't set the errno (like registry APIs in Win32))
479 DECLARE_LOG_FUNCTION2(SysError
, long lErrCode
);
481 // debug functions do nothing in release mode
483 DECLARE_LOG_FUNCTION(Debug
);
485 // first kind of LogTrace is unconditional: it doesn't check the level,
486 DECLARE_LOG_FUNCTION(Trace
);
488 // this second version will only log the message if the mask had been
489 // added to the list of masks with AddTraceMask()
490 DECLARE_LOG_FUNCTION2(Trace
, const wxChar
*mask
);
492 // the last one does nothing if all of level bits are not set
493 // in wxLog::GetActive()->GetTraceMask() - it's deprecated in favour of
494 // string identifiers
495 DECLARE_LOG_FUNCTION2(Trace
, wxTraceMask mask
);
497 // these functions do nothing in release builds
498 inline void wxVLogDebug(const wxChar
*, va_list) { }
499 inline void wxLogDebug(const wxChar
*, ...) { }
500 inline void wxVLogTrace(const wxChar
*, va_list) { }
501 inline void wxLogTrace(const wxChar
*, ...) { }
502 inline void wxVLogTrace(wxTraceMask
, const wxChar
*, va_list) { }
503 inline void wxLogTrace(wxTraceMask
, const wxChar
*, ...) { }
504 inline void wxVLogTrace(const wxChar
*, const wxChar
*, va_list) { }
505 inline void wxLogTrace(const wxChar
*, const wxChar
*, ...) { }
506 #endif // debug/!debug
508 // wxLogFatalError helper: show the (fatal) error to the user in a safe way,
509 // i.e. without using wxMessageBox() for example because it could crash
510 void WXDLLIMPEXP_BASE
511 wxSafeShowMessage(const wxString
& title
, const wxString
& text
);
513 // ----------------------------------------------------------------------------
514 // debug only logging functions: use them with API name and error code
515 // ----------------------------------------------------------------------------
518 // make life easier for people using VC++ IDE: clicking on the message
519 // will take us immediately to the place of the failed API
521 #define wxLogApiError(api, rc) \
522 wxLogDebug(wxT("%s(%d): '%s' failed with error 0x%08lx (%s)."), \
523 __TFILE__, __LINE__, api, \
524 (long)rc, wxSysErrorMsg(rc))
526 #define wxLogApiError(api, rc) \
527 wxLogDebug(wxT("In file %s at line %d: '%s' failed with " \
528 "error 0x%08lx (%s)."), \
529 __TFILE__, __LINE__, api, \
530 (long)rc, wxSysErrorMsg(rc))
533 #define wxLogLastError(api) wxLogApiError(api, wxSysErrorCode())
536 inline void wxLogApiError(const wxChar
*, long) { }
537 inline void wxLogLastError(const wxChar
*) { }
538 #endif //debug/!debug