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 license
10 /////////////////////////////////////////////////////////////////////////////
15 #if defined(__GNUG__) && !defined(__APPLE__)
16 #pragma interface "log.h"
20 #include "wx/string.h"
22 // ----------------------------------------------------------------------------
23 // forward declarations
24 // ----------------------------------------------------------------------------
26 class WXDLLEXPORT wxTextCtrl
;
27 class WXDLLEXPORT wxLogFrame
;
28 class WXDLLEXPORT wxFrame
;
30 // ----------------------------------------------------------------------------
32 // ----------------------------------------------------------------------------
34 typedef unsigned long wxTraceMask
;
35 typedef unsigned long wxLogLevel
;
37 // ----------------------------------------------------------------------------
39 // ----------------------------------------------------------------------------
44 #include <time.h> // for time_t
47 #include "wx/dynarray.h"
49 // ----------------------------------------------------------------------------
51 // ----------------------------------------------------------------------------
53 // different standard log levels (you may also define your own)
56 wxLOG_FatalError
, // program can't continue, abort immediately
57 wxLOG_Error
, // a serious error, user must be informed about it
58 wxLOG_Warning
, // user is normally informed about it but may be ignored
59 wxLOG_Message
, // normal message (i.e. normal output of a non GUI app)
60 wxLOG_Info
, // informational message (a.k.a. 'Verbose')
61 wxLOG_Status
, // informational: might go to the status line of GUI app
62 wxLOG_Debug
, // never shown to the user, disabled in release mode
63 wxLOG_Trace
, // trace messages are also only enabled in debug mode
64 wxLOG_Progress
, // used for progress indicator (not yet)
65 wxLOG_User
= 100 // user defined levels start here
68 // symbolic trace masks - wxLogTrace("foo", "some trace message...") will be
69 // discarded unless the string "foo" has been added to the list of allowed
70 // ones with AddTraceMask()
72 #define wxTRACE_MemAlloc wxT("memalloc") // trace memory allocation (new/delete)
73 #define wxTRACE_Messages wxT("messages") // trace window messages/X callbacks
74 #define wxTRACE_ResAlloc wxT("resalloc") // trace GDI resource allocation
75 #define wxTRACE_RefCount wxT("refcount") // trace various ref counting operations
78 #define wxTRACE_OleCalls wxT("ole") // OLE interface calls
81 // the trace masks have been superceded by symbolic trace constants, they're
82 // for compatibility only andwill be removed soon - do NOT use them
84 // meaning of different bits of the trace mask (which allows selectively
85 // enable/disable some trace messages)
86 #define wxTraceMemAlloc 0x0001 // trace memory allocation (new/delete)
87 #define wxTraceMessages 0x0002 // trace window messages/X callbacks
88 #define wxTraceResAlloc 0x0004 // trace GDI resource allocation
89 #define wxTraceRefCount 0x0008 // trace various ref counting operations
92 #define wxTraceOleCalls 0x0100 // OLE interface calls
95 #include "wx/ioswrap.h"
97 // ----------------------------------------------------------------------------
98 // derive from this class to redirect (or suppress, or ...) log messages
99 // normally, only a single instance of this class exists but it's not enforced
100 // ----------------------------------------------------------------------------
102 class WXDLLEXPORT wxLog
109 // Allow replacement of the fixed size static buffer with
110 // a user allocated one. Pass in NULL to restore the
111 // built in static buffer.
112 static wxChar
*SetLogBuffer( wxChar
*buf
, size_t size
= 0 );
114 // these functions allow to completely disable all log messages
115 // is logging disabled now?
116 static bool IsEnabled() { return ms_doLog
; }
117 // change the flag state, return the previous one
118 static bool EnableLogging(bool doIt
= TRUE
)
119 { bool doLogOld
= ms_doLog
; ms_doLog
= doIt
; return doLogOld
; }
121 // static sink function - see DoLog() for function to overload in the
123 static void OnLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
126 wxLog
*pLogger
= GetActiveTarget();
128 pLogger
->DoLog(level
, szString
, t
);
133 // flush shows all messages if they're not logged immediately (FILE
134 // and iostream logs don't need it, but wxGuiLog does to avoid showing
135 // 17 modal dialogs one after another)
136 virtual void Flush();
137 // call to Flush() may be optimized: call it only if this function
138 // returns true (although Flush() also returns immediately if there is
139 // no messages, this functions is more efficient because inline)
140 bool HasPendingMessages() const { return m_bHasMessages
; }
142 // only one sink is active at each moment
143 // flush the active target if any
144 static void FlushActive()
146 if ( !ms_suspendCount
)
148 wxLog
*log
= GetActiveTarget();
149 if ( log
&& log
->HasPendingMessages() )
153 // get current log target, will call wxApp::CreateLogTarget() to
154 // create one if none exists
155 static wxLog
*GetActiveTarget();
156 // change log target, pLogger may be NULL
157 static wxLog
*SetActiveTarget(wxLog
*pLogger
);
159 // suspend the message flushing of the main target until the next call
160 // to Resume() - this is mainly for internal use (to prevent wxYield()
161 // from flashing the messages)
162 static void Suspend() { ms_suspendCount
++; }
163 // must be called for each Suspend()!
164 static void Resume() { ms_suspendCount
--; }
166 // functions controlling the default wxLog behaviour
167 // verbose mode is activated by standard command-line '-verbose'
169 static void SetVerbose(bool bVerbose
= TRUE
) { ms_bVerbose
= bVerbose
; }
170 // should GetActiveTarget() try to create a new log object if the
172 static void DontCreateOnDemand();
174 // trace mask (see wxTraceXXX constants for details)
175 static void SetTraceMask(wxTraceMask ulMask
) { ms_ulTraceMask
= ulMask
; }
176 // add string trace mask
177 static void AddTraceMask(const wxString
& str
) { ms_aTraceMasks
.Add(str
); }
178 // add string trace mask
179 static void RemoveTraceMask(const wxString
& str
);
180 // remove all string trace masks
181 static void ClearTraceMasks();
182 // get string trace masks
183 static const wxArrayString
&GetTraceMasks() { return ms_aTraceMasks
; }
185 // sets the timestamp string: this is used as strftime() format string
186 // for the log targets which add time stamps to the messages - set it
187 // to NULL to disable time stamping completely.
188 static void SetTimestamp(const wxChar
*ts
) { ms_timestamp
= ts
; }
191 // gets the verbose status
192 static bool GetVerbose() { return ms_bVerbose
; }
194 static wxTraceMask
GetTraceMask() { return ms_ulTraceMask
; }
195 // is this trace mask in the list?
196 static bool IsAllowedTraceMask(const wxChar
*mask
)
197 { return ms_aTraceMasks
.Index(mask
) != wxNOT_FOUND
; }
199 // get the current timestamp format string (may be NULL)
200 static const wxChar
*GetTimestamp() { return ms_timestamp
; }
203 // put the time stamp into the string if ms_timestamp != NULL (don't
204 // change it otherwise)
205 static void TimeStamp(wxString
*str
);
207 // make dtor virtual for all derived classes
211 bool m_bHasMessages
; // any messages in the queue?
213 // the logging functions that can be overriden
214 // default DoLog() prepends the time stamp and a prefix corresponding
215 // to the message to szString and then passes it to DoLogString()
216 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
217 // default DoLogString does nothing but is not pure virtual because if
218 // you override DoLog() you might not need it at all
219 virtual void DoLogString(const wxChar
*szString
, time_t t
);
225 static wxLog
*ms_pLogger
; // currently active log sink
226 static bool ms_doLog
; // FALSE => all logging disabled
227 static bool ms_bAutoCreate
; // create new log targets on demand?
228 static bool ms_bVerbose
; // FALSE => ignore LogInfo messages
230 static size_t ms_suspendCount
; // if positive, logs are not flushed
232 // format string for strftime(), if NULL, time stamping log messages is
234 static const wxChar
*ms_timestamp
;
236 static wxTraceMask ms_ulTraceMask
; // controls wxLogTrace behaviour
237 static wxArrayString ms_aTraceMasks
; // more powerful filter for wxLogTrace
240 // ----------------------------------------------------------------------------
241 // "trivial" derivations of wxLog
242 // ----------------------------------------------------------------------------
244 // log everything to a "FILE *", stderr by default
245 class WXDLLEXPORT wxLogStderr
: public wxLog
247 DECLARE_NO_COPY_CLASS(wxLogStderr
)
250 // redirect log output to a FILE
251 wxLogStderr(FILE *fp
= (FILE *) NULL
);
254 // implement sink function
255 virtual void DoLogString(const wxChar
*szString
, time_t t
);
260 #if wxUSE_STD_IOSTREAM
262 // log everything to an "ostream", cerr by default
263 class WXDLLEXPORT wxLogStream
: public wxLog
266 // redirect log output to an ostream
267 wxLogStream(wxSTD ostream
*ostr
= (wxSTD ostream
*) NULL
);
270 // implement sink function
271 virtual void DoLogString(const wxChar
*szString
, time_t t
);
273 // using ptr here to avoid including <iostream.h> from this file
274 wxSTD ostream
*m_ostr
;
277 #endif // wxUSE_STD_IOSTREAM
279 // ----------------------------------------------------------------------------
280 // /dev/null log target: suppress logging until this object goes out of scope
281 // ----------------------------------------------------------------------------
289 // wxFile.Open() normally complains if file can't be opened, we don't
293 if ( !file.Open("bar") )
294 ... process error ourselves ...
296 // ~wxLogNull called, old log sink restored
299 class WXDLLEXPORT wxLogNull
302 wxLogNull() : m_flagOld(wxLog::EnableLogging(FALSE
)) { }
303 ~wxLogNull() { (void)wxLog::EnableLogging(m_flagOld
); }
306 bool m_flagOld
; // the previous value of the wxLog::ms_doLog
309 // ----------------------------------------------------------------------------
310 // chaining log target: installs itself as a log target and passes all
311 // messages to the real log target given to it in the ctor but also forwards
312 // them to the previously active one
314 // note that you don't have to call SetActiveTarget() with this class, it
315 // does it itself in its ctor
316 // ----------------------------------------------------------------------------
318 class WXDLLEXPORT wxLogChain
: public wxLog
321 wxLogChain(wxLog
*logger
);
322 virtual ~wxLogChain();
324 // change the new log target
325 void SetLog(wxLog
*logger
);
327 // this can be used to temporarily disable (and then reenable) passing
328 // messages to the old logger (by default we do pass them)
329 void PassMessages(bool bDoPass
) { m_bPassMessages
= bDoPass
; }
331 // are we passing the messages to the previous log target?
332 bool IsPassingMessages() const { return m_bPassMessages
; }
334 // return the previous log target (may be NULL)
335 wxLog
*GetOldLog() const { return m_logOld
; }
337 // override base class version to flush the old logger as well
338 virtual void Flush();
341 // pass the chain to the old logger if needed
342 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
345 // the current log target
348 // the previous log target
351 // do we pass the messages to the old logger?
352 bool m_bPassMessages
;
355 // a chain log target which uses itself as the new logger
356 class WXDLLEXPORT wxLogPassThrough
: public wxLogChain
362 // ----------------------------------------------------------------------------
363 // the following log targets are only compiled in if the we're compiling the
364 // GUI part (andnot just the base one) of the library, they're implemented in
365 // src/generic/logg.cpp *and not src/common/log.cpp unlike all the rest)
366 // ----------------------------------------------------------------------------
372 // log everything to a text window (GUI only of course)
373 class WXDLLEXPORT wxLogTextCtrl
: public wxLog
376 wxLogTextCtrl(wxTextCtrl
*pTextCtrl
);
379 // implement sink function
380 virtual void DoLogString(const wxChar
*szString
, time_t t
);
382 // the control we use
383 wxTextCtrl
*m_pTextCtrl
;
386 #endif // wxUSE_TEXTCTRL
388 // ----------------------------------------------------------------------------
389 // GUI log target, the default one for wxWindows programs
390 // ----------------------------------------------------------------------------
394 class WXDLLEXPORT wxLogGui
: public wxLog
400 // show all messages that were logged since the last Flush()
401 virtual void Flush();
404 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
409 wxArrayString m_aMessages
; // the log message texts
410 wxArrayInt m_aSeverity
; // one of wxLOG_XXX values
411 wxArrayLong m_aTimes
; // the time of each message
412 bool m_bErrors
, // do we have any errors?
413 m_bWarnings
; // any warnings?
416 #endif // wxUSE_LOGGUI
418 // ----------------------------------------------------------------------------
419 // (background) log window: this class forwards all log messages to the log
420 // target which was active when it was instantiated, but also collects them
421 // to the log window. This window has it's own menu which allows the user to
422 // close it, clear the log contents or save it to the file.
423 // ----------------------------------------------------------------------------
427 class WXDLLEXPORT wxLogWindow
: public wxLogPassThrough
430 wxLogWindow(wxFrame
*pParent
, // the parent frame (can be NULL)
431 const wxChar
*szTitle
, // the title of the frame
432 bool bShow
= TRUE
, // show window immediately?
433 bool bPassToOld
= TRUE
); // pass messages to the old target?
438 // show/hide the log window
439 void Show(bool bShow
= TRUE
);
440 // retrieve the pointer to the frame
441 wxFrame
*GetFrame() const;
444 // called immediately after the log frame creation allowing for
445 // any extra initializations
446 virtual void OnFrameCreate(wxFrame
*frame
);
447 // called if the user closes the window interactively, will not be
448 // called if it is destroyed for another reason (such as when program
449 // exits) - return TRUE from here to allow the frame to close, FALSE
450 // to prevent this from happening
451 virtual bool OnFrameClose(wxFrame
*frame
);
452 // called right before the log frame is going to be deleted: will
453 // always be called unlike OnFrameClose()
454 virtual void OnFrameDelete(wxFrame
*frame
);
457 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
458 virtual void DoLogString(const wxChar
*szString
, time_t t
);
461 wxLogFrame
*m_pLogFrame
; // the log frame
464 #endif // wxUSE_LOGWINDOW
468 // ============================================================================
470 // ============================================================================
472 // ----------------------------------------------------------------------------
473 // Log functions should be used by application instead of stdio, iostream &c
474 // for log messages for easy redirection
475 // ----------------------------------------------------------------------------
477 // ----------------------------------------------------------------------------
478 // get error code/error message from system in a portable way
479 // ----------------------------------------------------------------------------
481 // return the last system error code
482 WXDLLEXPORT
unsigned long wxSysErrorCode();
484 // return the error message for given (or last if 0) error code
485 WXDLLEXPORT
const wxChar
* wxSysErrorMsg(unsigned long nErrCode
= 0);
487 // ----------------------------------------------------------------------------
488 // define wxLog<level>
489 // ----------------------------------------------------------------------------
491 #define DECLARE_LOG_FUNCTION(level) \
492 extern void WXDLLEXPORT wxVLog##level(const wxChar *szFormat, \
494 extern void WXDLLEXPORT wxLog##level(const wxChar *szFormat, \
495 ...) ATTRIBUTE_PRINTF_1
496 #define DECLARE_LOG_FUNCTION2(level, arg1) \
497 extern void WXDLLEXPORT wxVLog##level(arg1, const wxChar *szFormat, \
499 extern void WXDLLEXPORT wxLog##level(arg1, const wxChar *szFormat, \
500 ...) ATTRIBUTE_PRINTF_2
504 // log functions do nothing at all
505 #define DECLARE_LOG_FUNCTION(level) \
506 inline void WXDLLEXPORT wxVLog##level(const wxChar *szFormat, \
508 inline void WXDLLEXPORT wxLog##level(const wxChar *szFormat, ...) {}
509 #define DECLARE_LOG_FUNCTION2(level, arg1) \
510 inline void WXDLLEXPORT wxVLog##level(arg1, const wxChar *szFormat, \
512 inline void WXDLLEXPORT wxLog##level(arg1, const wxChar *szFormat, ...) {}
514 #endif // wxUSE_LOG/!wxUSE_LOG
516 // a generic function for all levels (level is passes as parameter)
517 DECLARE_LOG_FUNCTION2(Generic
, wxLogLevel level
);
519 // one function per each level
520 DECLARE_LOG_FUNCTION(FatalError
);
521 DECLARE_LOG_FUNCTION(Error
);
522 DECLARE_LOG_FUNCTION(Warning
);
523 DECLARE_LOG_FUNCTION(Message
);
524 DECLARE_LOG_FUNCTION(Info
);
525 DECLARE_LOG_FUNCTION(Verbose
);
527 // this function sends the log message to the status line of the top level
528 // application frame, if any
529 DECLARE_LOG_FUNCTION(Status
);
531 // this one is the same as previous except that it allows to explicitly
532 // specify the frame to which the output should go
533 DECLARE_LOG_FUNCTION2(Status
, wxFrame
*pFrame
);
535 // additional one: as wxLogError, but also logs last system call error code
536 // and the corresponding error message if available
537 DECLARE_LOG_FUNCTION(SysError
);
539 // and another one which also takes the error code (for those broken APIs
540 // that don't set the errno (like registry APIs in Win32))
541 DECLARE_LOG_FUNCTION2(SysError
, long lErrCode
);
543 // debug functions do nothing in release mode
545 DECLARE_LOG_FUNCTION(Debug
);
547 // first kind of LogTrace is unconditional: it doesn't check the level,
548 DECLARE_LOG_FUNCTION(Trace
);
550 // this second version will only log the message if the mask had been
551 // added to the list of masks with AddTraceMask()
552 DECLARE_LOG_FUNCTION2(Trace
, const wxChar
*mask
);
554 // the last one does nothing if all of level bits are not set
555 // in wxLog::GetActive()->GetTraceMask() - it's deprecated in favour of
556 // string identifiers
557 DECLARE_LOG_FUNCTION2(Trace
, wxTraceMask mask
);
559 // these functions do nothing in release builds
560 inline void wxVLogDebug(const wxChar
*, va_list) { }
561 inline void wxLogDebug(const wxChar
*, ...) { }
562 inline void wxVLogTrace(const wxChar
*, va_list) { }
563 inline void wxLogTrace(const wxChar
*, ...) { }
564 inline void wxVLogTrace(wxTraceMask
, const wxChar
*, va_list) { }
565 inline void wxLogTrace(wxTraceMask
, const wxChar
*, ...) { }
566 inline void wxVLogTrace(const wxChar
*, const wxChar
*, va_list) { }
567 inline void wxLogTrace(const wxChar
*, const wxChar
*, ...) { }
568 #endif // debug/!debug
570 // wxLogFatalError helper: show the (fatal) error to the user in a safe way,
571 // i.e. without using wxMessageBox() for example because it could crash
572 void WXDLLEXPORT
wxSafeShowMessage(const wxString
& title
, const wxString
& text
);
574 // ----------------------------------------------------------------------------
575 // debug only logging functions: use them with API name and error code
576 // ----------------------------------------------------------------------------
579 // make life easier for people using VC++ IDE: clicking on the message
580 // will take us immediately to the place of the failed API
582 #define wxLogApiError(api, rc) \
583 wxLogDebug(wxT("%s(%d): '%s' failed with error 0x%08lx (%s)."), \
584 __TFILE__, __LINE__, api, \
585 (long)rc, wxSysErrorMsg(rc))
587 #define wxLogApiError(api, rc) \
588 wxLogDebug(wxT("In file %s at line %d: '%s' failed with " \
589 "error 0x%08lx (%s)."), \
590 __TFILE__, __LINE__, api, \
591 (long)rc, wxSysErrorMsg(rc))
594 #define wxLogLastError(api) wxLogApiError(api, wxSysErrorCode())
597 inline void wxLogApiError(const wxChar
*, long) { }
598 inline void wxLogLastError(const wxChar
*) { }
599 #endif //debug/!debug