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 /////////////////////////////////////////////////////////////////////////////
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 // ----------------------------------------------------------------------------
43 #include <time.h> // for time_t
45 #include "wx/dynarray.h"
47 // ----------------------------------------------------------------------------
49 // ----------------------------------------------------------------------------
51 // different standard log levels (you may also define your own)
54 wxLOG_FatalError
, // program can't continue, abort immediately
55 wxLOG_Error
, // a serious error, user must be informed about it
56 wxLOG_Warning
, // user is normally informed about it but may be ignored
57 wxLOG_Message
, // normal message (i.e. normal output of a non GUI app)
58 wxLOG_Info
, // informational message (a.k.a. 'Verbose')
59 wxLOG_Status
, // informational: might go to the status line of GUI app
60 wxLOG_Debug
, // never shown to the user, disabled in release mode
61 wxLOG_Trace
, // trace messages are also only enabled in debug mode
62 wxLOG_Progress
, // used for progress indicator (not yet)
63 wxLOG_User
= 100 // user defined levels start here
66 // symbolic trace masks - wxLogTrace("foo", "some trace message...") will be
67 // discarded unless the string "foo" has been added to the list of allowed
68 // ones with AddTraceMask()
70 #define wxTRACE_MemAlloc wxT("memalloc") // trace memory allocation (new/delete)
71 #define wxTRACE_Messages wxT("messages") // trace window messages/X callbacks
72 #define wxTRACE_ResAlloc wxT("resalloc") // trace GDI resource allocation
73 #define wxTRACE_RefCount wxT("refcount") // trace various ref counting operations
76 #define wxTRACE_OleCalls wxT("ole") // OLE interface calls
79 // the trace masks have been superceded by symbolic trace constants, they're
80 // for compatibility only andwill be removed soon - do NOT use them
82 // meaning of different bits of the trace mask (which allows selectively
83 // enable/disable some trace messages)
84 #define wxTraceMemAlloc 0x0001 // trace memory allocation (new/delete)
85 #define wxTraceMessages 0x0002 // trace window messages/X callbacks
86 #define wxTraceResAlloc 0x0004 // trace GDI resource allocation
87 #define wxTraceRefCount 0x0008 // trace various ref counting operations
90 #define wxTraceOleCalls 0x0100 // OLE interface calls
93 #include "wx/ioswrap.h"
95 // ----------------------------------------------------------------------------
96 // derive from this class to redirect (or suppress, or ...) log messages
97 // normally, only a single instance of this class exists but it's not enforced
98 // ----------------------------------------------------------------------------
100 class WXDLLEXPORT wxLog
106 // these functions allow to completely disable all log messages
107 // is logging disabled now?
108 static bool IsEnabled() { return ms_doLog
; }
109 // change the flag state, return the previous one
110 static bool EnableLogging(bool doIt
= TRUE
)
111 { bool doLogOld
= ms_doLog
; ms_doLog
= doIt
; return doLogOld
; }
113 // static sink function - see DoLog() for function to overload in the
115 static void OnLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
118 wxLog
*pLogger
= GetActiveTarget();
120 pLogger
->DoLog(level
, szString
, t
);
125 // flush shows all messages if they're not logged immediately (FILE
126 // and iostream logs don't need it, but wxGuiLog does to avoid showing
127 // 17 modal dialogs one after another)
128 virtual void Flush();
129 // call to Flush() may be optimized: call it only if this function
130 // returns true (although Flush() also returns immediately if there is
131 // no messages, this functions is more efficient because inline)
132 bool HasPendingMessages() const { return m_bHasMessages
; }
134 // only one sink is active at each moment
135 // flush the active target if any
136 static void FlushActive()
138 if ( !ms_suspendCount
)
140 wxLog
*log
= GetActiveTarget();
141 if ( log
&& log
->HasPendingMessages() )
145 // get current log target, will call wxApp::CreateLogTarget() to
146 // create one if none exists
147 static wxLog
*GetActiveTarget();
148 // change log target, pLogger may be NULL
149 static wxLog
*SetActiveTarget(wxLog
*pLogger
);
151 // suspend the message flushing of the main target until the next call
152 // to Resume() - this is mainly for internal use (to prevent wxYield()
153 // from flashing the messages)
154 static void Suspend() { ms_suspendCount
++; }
155 // must be called for each Suspend()!
156 static void Resume() { ms_suspendCount
--; }
158 // functions controlling the default wxLog behaviour
159 // verbose mode is activated by standard command-line '-verbose'
161 static void SetVerbose(bool bVerbose
= TRUE
) { ms_bVerbose
= bVerbose
; }
162 // should GetActiveTarget() try to create a new log object if the
164 static void DontCreateOnDemand();
166 // trace mask (see wxTraceXXX constants for details)
167 static void SetTraceMask(wxTraceMask ulMask
) { ms_ulTraceMask
= ulMask
; }
168 // add string trace mask
169 static void AddTraceMask(const wxString
& str
) { ms_aTraceMasks
.Add(str
); }
170 // add string trace mask
171 static void RemoveTraceMask(const wxString
& str
);
172 // remove all string trace masks
173 static void ClearTraceMasks();
175 // sets the timestamp string: this is used as strftime() format string
176 // for the log targets which add time stamps to the messages - set it
177 // to NULL to disable time stamping completely.
178 static void SetTimestamp(const wxChar
*ts
) { ms_timestamp
= ts
; }
181 // gets the verbose status
182 static bool GetVerbose() { return ms_bVerbose
; }
184 static wxTraceMask
GetTraceMask() { return ms_ulTraceMask
; }
185 // is this trace mask in the list?
186 static bool IsAllowedTraceMask(const wxChar
*mask
)
187 { return ms_aTraceMasks
.Index(mask
) != wxNOT_FOUND
; }
189 // get the current timestamp format string (may be NULL)
190 static const wxChar
*GetTimestamp() { return ms_timestamp
; }
193 // put the time stamp into the string if ms_timestamp != NULL (don't
194 // change it otherwise)
195 static void TimeStamp(wxString
*str
);
197 // make dtor virtual for all derived classes
201 bool m_bHasMessages
; // any messages in the queue?
203 // the logging functions that can be overriden
204 // default DoLog() prepends the time stamp and a prefix corresponding
205 // to the message to szString and then passes it to DoLogString()
206 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
207 // default DoLogString does nothing but is not pure virtual because if
208 // you override DoLog() you might not need it at all
209 virtual void DoLogString(const wxChar
*szString
, time_t t
);
215 static wxLog
*ms_pLogger
; // currently active log sink
216 static bool ms_doLog
; // FALSE => all logging disabled
217 static bool ms_bAutoCreate
; // create new log targets on demand?
218 static bool ms_bVerbose
; // FALSE => ignore LogInfo messages
220 static size_t ms_suspendCount
; // if positive, logs are not flushed
222 // format string for strftime(), if NULL, time stamping log messages is
224 static const wxChar
*ms_timestamp
;
226 static wxTraceMask ms_ulTraceMask
; // controls wxLogTrace behaviour
227 static wxArrayString ms_aTraceMasks
; // more powerful filter for wxLogTrace
230 // ----------------------------------------------------------------------------
231 // "trivial" derivations of wxLog
232 // ----------------------------------------------------------------------------
234 // log everything to a "FILE *", stderr by default
235 class WXDLLEXPORT wxLogStderr
: public wxLog
238 // redirect log output to a FILE
239 wxLogStderr(FILE *fp
= (FILE *) NULL
);
242 // implement sink function
243 virtual void DoLogString(const wxChar
*szString
, time_t t
);
248 #if wxUSE_STD_IOSTREAM
250 // log everything to an "ostream", cerr by default
251 class WXDLLEXPORT wxLogStream
: public wxLog
254 // redirect log output to an ostream
255 wxLogStream(wxSTD ostream
*ostr
= (wxSTD ostream
*) NULL
);
258 // implement sink function
259 virtual void DoLogString(const wxChar
*szString
, time_t t
);
261 // using ptr here to avoid including <iostream.h> from this file
262 wxSTD ostream
*m_ostr
;
265 #endif // wxUSE_STD_IOSTREAM
267 // the following log targets are only compiled in if the we're compiling the
268 // GUI part (andnot just the base one) of the library, they're implemented in
269 // src/generic/logg.cpp *and not src/common/log.cpp unlike all the rest)
275 // log everything to a text window (GUI only of course)
276 class WXDLLEXPORT wxLogTextCtrl
: public wxLog
279 wxLogTextCtrl(wxTextCtrl
*pTextCtrl
);
282 // implement sink function
283 virtual void DoLogString(const wxChar
*szString
, time_t t
);
285 // the control we use
286 wxTextCtrl
*m_pTextCtrl
;
289 #endif // wxUSE_TEXTCTRL
291 // ----------------------------------------------------------------------------
292 // /dev/null log target: suppress logging until this object goes out of scope
293 // ----------------------------------------------------------------------------
301 // wxFile.Open() normally complains if file can't be opened, we don't
305 if ( !file.Open("bar") )
306 ... process error ourselves ...
308 // ~wxLogNull called, old log sink restored
311 class WXDLLEXPORT wxLogNull
314 wxLogNull() { m_flagOld
= wxLog::EnableLogging(FALSE
); }
315 ~wxLogNull() { (void)wxLog::EnableLogging(m_flagOld
); }
318 bool m_flagOld
; // the previous value of the wxLog::ms_doLog
321 // ----------------------------------------------------------------------------
322 // chaining log target: installs itself as a log target and passes all
323 // messages to the real log target given to it in the ctor but also forwards
324 // them to the previously active one
326 // note that you don't have to call SetActiveTarget() with this class, it
327 // does it itself in its ctor
328 // ----------------------------------------------------------------------------
330 class WXDLLEXPORT wxLogChain
: public wxLog
333 wxLogChain(wxLog
*logger
);
334 virtual ~wxLogChain() { delete m_logOld
; }
336 // change the new log target
337 void SetLog(wxLog
*logger
);
339 // this can be used to temporarily disable (and then reenable) passing
340 // messages to the old logger (by default we do pass them)
341 void PassMessages(bool bDoPass
) { m_bPassMessages
= bDoPass
; }
343 // are we passing the messages to the previous log target?
344 bool IsPassingMessages() const { return m_bPassMessages
; }
346 // return the previous log target (may be NULL)
347 wxLog
*GetOldLog() const { return m_logOld
; }
349 // override base class version to flush the old logger as well
350 virtual void Flush();
353 // pass the chain to the old logger if needed
354 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
357 // the current log target
360 // the previous log target
363 // do we pass the messages to the old logger?
364 bool m_bPassMessages
;
367 // a chain log target which uses itself as the new logger
368 class WXDLLEXPORT wxLogPassThrough
: public wxLogChain
371 wxLogPassThrough() : wxLogChain(this) { }
374 // ----------------------------------------------------------------------------
375 // GUI log target, the default one for wxWindows programs
376 // ----------------------------------------------------------------------------
380 class WXDLLEXPORT wxLogGui
: public wxLog
386 // show all messages that were logged since the last Flush()
387 virtual void Flush();
390 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
395 wxArrayString m_aMessages
; // the log message texts
396 wxArrayInt m_aSeverity
; // one of wxLOG_XXX values
397 wxArrayLong m_aTimes
; // the time of each message
398 bool m_bErrors
, // do we have any errors?
399 m_bWarnings
; // any warnings?
402 #endif // wxUSE_LOGGUI
404 // ----------------------------------------------------------------------------
405 // (background) log window: this class forwards all log messages to the log
406 // target which was active when it was instantiated, but also collects them
407 // to the log window. This window has it's own menu which allows the user to
408 // close it, clear the log contents or save it to the file.
409 // ----------------------------------------------------------------------------
413 class WXDLLEXPORT wxLogWindow
: public wxLogPassThrough
416 wxLogWindow(wxFrame
*pParent
, // the parent frame (can be NULL)
417 const wxChar
*szTitle
, // the title of the frame
418 bool bShow
= TRUE
, // show window immediately?
419 bool bPassToOld
= TRUE
); // pass messages to the old target?
424 // show/hide the log window
425 void Show(bool bShow
= TRUE
);
426 // retrieve the pointer to the frame
427 wxFrame
*GetFrame() const;
430 // called immediately after the log frame creation allowing for
431 // any extra initializations
432 virtual void OnFrameCreate(wxFrame
*frame
);
433 // called if the user closes the window interactively, will not be
434 // called if it is destroyed for another reason (such as when program
435 // exits) - return TRUE from here to allow the frame to close, FALSE
436 // to prevent this from happening
437 virtual bool OnFrameClose(wxFrame
*frame
);
438 // called right before the log frame is going to be deleted: will
439 // always be called unlike OnFrameClose()
440 virtual void OnFrameDelete(wxFrame
*frame
);
443 virtual void DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
);
444 virtual void DoLogString(const wxChar
*szString
, time_t t
);
447 wxLogFrame
*m_pLogFrame
; // the log frame
450 #endif // wxUSE_LOGWINDOW
454 // ============================================================================
456 // ============================================================================
458 // ----------------------------------------------------------------------------
459 // Log functions should be used by application instead of stdio, iostream &c
460 // for log messages for easy redirection
461 // ----------------------------------------------------------------------------
463 // ----------------------------------------------------------------------------
464 // get error code/error message from system in a portable way
465 // ----------------------------------------------------------------------------
467 // return the last system error code
468 WXDLLEXPORT
unsigned long wxSysErrorCode();
469 // return the error message for given (or last if 0) error code
470 WXDLLEXPORT
const wxChar
* wxSysErrorMsg(unsigned long nErrCode
= 0);
472 // define wxLog<level>
473 // -------------------
475 #define DECLARE_LOG_FUNCTION(level) \
476 extern void WXDLLEXPORT wxLog##level(const wxChar *szFormat, ...)
477 #define DECLARE_LOG_FUNCTION2(level, arg1) \
478 extern void WXDLLEXPORT wxLog##level(arg1, const wxChar *szFormat, ...)
482 // log functions do nothing at all
483 #define DECLARE_LOG_FUNCTION(level) \
484 inline void WXDLLEXPORT wxLog##level(const wxChar *szFormat, ...) {}
485 #define DECLARE_LOG_FUNCTION2(level, arg1) \
486 inline void WXDLLEXPORT wxLog##level(arg1, const wxChar *szFormat, ...) {}
488 #endif // wxUSE_LOG/!wxUSE_LOG
490 // a generic function for all levels (level is passes as parameter)
491 DECLARE_LOG_FUNCTION2(Generic
, wxLogLevel level
);
493 // one function per each level
494 DECLARE_LOG_FUNCTION(FatalError
);
495 DECLARE_LOG_FUNCTION(Error
);
496 DECLARE_LOG_FUNCTION(Warning
);
497 DECLARE_LOG_FUNCTION(Message
);
498 DECLARE_LOG_FUNCTION(Info
);
499 DECLARE_LOG_FUNCTION(Verbose
);
501 // this function sends the log message to the status line of the top level
502 // application frame, if any
503 DECLARE_LOG_FUNCTION(Status
);
505 // this one is the same as previous except that it allows to explicitly
506 // specify the frame to which the output should go
507 DECLARE_LOG_FUNCTION2(Status
, wxFrame
*pFrame
);
509 // additional one: as wxLogError, but also logs last system call error code
510 // and the corresponding error message if available
511 DECLARE_LOG_FUNCTION(SysError
);
513 // and another one which also takes the error code (for those broken APIs
514 // that don't set the errno (like registry APIs in Win32))
515 DECLARE_LOG_FUNCTION2(SysError
, long lErrCode
);
517 // debug functions do nothing in release mode
519 DECLARE_LOG_FUNCTION(Debug
);
521 // first king of LogTrace is uncoditional: it doesn't check the level,
522 DECLARE_LOG_FUNCTION(Trace
);
524 // this second version will only log the message if the mask had been
525 // added to the list of masks with AddTraceMask()
526 DECLARE_LOG_FUNCTION2(Trace
, const wxChar
*mask
);
528 // the last one does nothing if all of level bits are not set
529 // in wxLog::GetActive()->GetTraceMask() - it's deprecated in favour of
530 // string identifiers
531 DECLARE_LOG_FUNCTION2(Trace
, wxTraceMask mask
);
533 // these functions do nothing in release builds
534 inline void wxLogDebug(const wxChar
*, ...) { }
535 inline void wxLogTrace(const wxChar
*, ...) { }
536 inline void wxLogTrace(wxTraceMask
, const wxChar
*, ...) { }
537 inline void wxLogTrace(const wxChar
*, const wxChar
*, ...) { }
538 #endif // debug/!debug
540 // ----------------------------------------------------------------------------
541 // debug only logging functions: use them with API name and error code
542 // ----------------------------------------------------------------------------
545 #define __XFILE__(x) Tx)
546 #define __TFILE__ __XFILE__(__FILE__)
550 // make life easier for people using VC++ IDE: clicking on the message
551 // will take us immediately to the place of the failed API
553 #define wxLogApiError(api, rc) \
554 wxLogDebug(wxT("%s(%d): '%s' failed with error 0x%08lx (%s)."), \
555 __TFILE__, __LINE__, api, \
556 rc, wxSysErrorMsg(rc))
558 #define wxLogApiError(api, rc) \
559 wxLogDebug(wxT("In file %s at line %d: '%s' failed with " \
560 "error 0x%08lx (%s)."), \
561 __TFILE__, __LINE__, api, \
562 rc, wxSysErrorMsg(rc))
565 #define wxLogLastError(api) wxLogApiError(api, wxSysErrorCode())
568 inline void wxLogApiError(const wxChar
*, long) { }
569 inline void wxLogLastError(const wxChar
*) { }
570 #endif //debug/!debug