]> git.saurik.com Git - wxWidgets.git/blob - include/wx/log.h
second try...
[wxWidgets.git] / include / wx / log.h
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: log.h
3 // Purpose: Assorted wxLogXXX functions, and wxLog (sink for logs)
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 29/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifndef _WX_LOG_H_
13 #define _WX_LOG_H_
14
15 #ifdef __GNUG__
16 #pragma interface "log.h"
17 #endif
18
19 #if wxUSE_LOG
20
21 #include <time.h> // for time_t
22
23 #include "wx/dynarray.h"
24
25 // ----------------------------------------------------------------------------
26 // constants
27 // ----------------------------------------------------------------------------
28
29 // different standard log levels (you may also define your own)
30 enum
31 {
32 wxLOG_FatalError, // program can't continue, abort immediately
33 wxLOG_Error, // a serious error, user must be informed about it
34 wxLOG_Warning, // user is normally informed about it but may be ignored
35 wxLOG_Message, // normal message (i.e. normal output of a non GUI app)
36 wxLOG_Info, // informational message (a.k.a. 'Verbose')
37 wxLOG_Status, // informational: might go to the status line of GUI app
38 wxLOG_Debug, // never shown to the user, disabled in release mode
39 wxLOG_Trace, // trace messages are also only enabled in debug mode
40 wxLOG_Progress, // used for progress indicator (not yet)
41 wxLOG_User = 100 // user defined levels start here
42 };
43
44 // symbolic trace masks - wxLogTrace("foo", "some trace message...") will be
45 // discarded unless the string "foo" has been added to the list of allowed
46 // ones with AddTraceMask()
47
48 #define wxTRACE_MemAlloc "memalloc" // trace memory allocation (new/delete)
49 #define wxTRACE_Messages "messages" // trace window messages/X callbacks
50 #define wxTRACE_ResAlloc "resalloc" // trace GDI resource allocation
51 #define wxTRACE_RefCount "refcount" // trace various ref counting operations
52
53 #ifdef __WXMSW__
54 #define wxTRACE_OleCalls "ole" // OLE interface calls
55 #endif
56
57 // the trace masks have been superceded by symbolic trace constants, they're
58 // for compatibility only andwill be removed soon - do NOT use them
59
60 // meaning of different bits of the trace mask (which allows selectively
61 // enable/disable some trace messages)
62 #define wxTraceMemAlloc 0x0001 // trace memory allocation (new/delete)
63 #define wxTraceMessages 0x0002 // trace window messages/X callbacks
64 #define wxTraceResAlloc 0x0004 // trace GDI resource allocation
65 #define wxTraceRefCount 0x0008 // trace various ref counting operations
66
67 #ifdef __WXMSW__
68 #define wxTraceOleCalls 0x0100 // OLE interface calls
69 #endif
70
71 typedef unsigned long wxTraceMask;
72 typedef unsigned long wxLogLevel;
73
74 // ----------------------------------------------------------------------------
75 // forward declarations
76 // ----------------------------------------------------------------------------
77
78 class WXDLLEXPORT wxTextCtrl;
79 class WXDLLEXPORT wxLogFrame;
80 class WXDLLEXPORT wxFrame;
81
82 #if wxUSE_IOSTREAMH
83 // N.B. BC++ doesn't have istream.h, ostream.h
84 # include <iostream.h>
85 #else
86 # include <ostream>
87 # if defined(__VISUALC__) || defined(__MWERKS__)
88 using namespace std;
89 # endif
90 #endif
91
92 // ----------------------------------------------------------------------------
93 // derive from this class to redirect (or suppress, or ...) log messages
94 // normally, only a single instance of this class exists but it's not enforced
95 // ----------------------------------------------------------------------------
96
97 class WXDLLEXPORT wxLog
98 {
99 public:
100 // ctor
101 wxLog();
102
103 // these functions allow to completely disable all log messages
104 // is logging disabled now?
105 static bool IsEnabled() { return ms_doLog; }
106 // change the flag state, return the previous one
107 static bool EnableLogging(bool doIt = TRUE)
108 { bool doLogOld = ms_doLog; ms_doLog = doIt; return doLogOld; }
109
110 // static sink function - see DoLog() for function to overload in the
111 // derived classes
112 static void OnLog(wxLogLevel level, const wxChar *szString, time_t t)
113 {
114 if ( IsEnabled() ) {
115 wxLog *pLogger = GetActiveTarget();
116 if ( pLogger )
117 pLogger->DoLog(level, szString, t);
118 }
119 }
120
121 // message buffering
122 // flush shows all messages if they're not logged immediately (FILE
123 // and iostream logs don't need it, but wxGuiLog does to avoid showing
124 // 17 modal dialogs one after another)
125 virtual void Flush();
126 // call to Flush() may be optimized: call it only if this function
127 // returns true (although Flush() also returns immediately if there is
128 // no messages, this functions is more efficient because inline)
129 bool HasPendingMessages() const { return m_bHasMessages; }
130
131 // only one sink is active at each moment
132 // get current log target, will call wxApp::CreateLogTarget() to
133 // create one if none exists
134 static wxLog *GetActiveTarget();
135 // change log target, pLogger may be NULL
136 static wxLog *SetActiveTarget(wxLog *pLogger);
137
138 // functions controlling the default wxLog behaviour
139 // verbose mode is activated by standard command-line '-verbose'
140 // option
141 void SetVerbose(bool bVerbose = TRUE) { m_bVerbose = bVerbose; }
142 // should GetActiveTarget() try to create a new log object if the
143 // current is NULL?
144 static void DontCreateOnDemand() { ms_bAutoCreate = FALSE; }
145
146 // trace mask (see wxTraceXXX constants for details)
147 static void SetTraceMask(wxTraceMask ulMask) { ms_ulTraceMask = ulMask; }
148 // add string trace mask
149 static void AddTraceMask(const wxString& str) { ms_aTraceMasks.Add(str); }
150 // add string trace mask
151 static void RemoveTraceMask(const wxString& str);
152
153 // accessors
154 // gets the verbose status
155 bool GetVerbose() const { return m_bVerbose; }
156 // get trace mask
157 static wxTraceMask GetTraceMask() { return ms_ulTraceMask; }
158 // is this trace mask in the list?
159 static bool IsAllowedTraceMask(const wxChar *mask)
160 { return ms_aTraceMasks.Index(mask) != wxNOT_FOUND; }
161
162 // make dtor virtual for all derived classes
163 virtual ~wxLog() { }
164
165 protected:
166 bool m_bHasMessages; // any messages in the queue?
167 bool m_bVerbose; // FALSE => ignore LogInfo messages
168
169 // the logging functions that can be overriden
170 // default DoLog() prepends the time stamp and a prefix corresponding
171 // to the message to szString and then passes it to DoLogString()
172 virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t);
173 // default DoLogString does nothing but is not pure virtual because if
174 // you override DoLog() you might not need it at all
175 virtual void DoLogString(const wxChar *szString, time_t t);
176
177 private:
178 // static variables
179 // ----------------
180
181 static wxLog *ms_pLogger; // currently active log sink
182 static bool ms_doLog; // FALSE => all logging disabled
183 static bool ms_bAutoCreate; // create new log targets on demand?
184
185 static wxTraceMask ms_ulTraceMask; // controls wxLogTrace behaviour
186 static wxArrayString ms_aTraceMasks; // more powerful filter for wxLogTrace
187 };
188
189 // ----------------------------------------------------------------------------
190 // "trivial" derivations of wxLog
191 // ----------------------------------------------------------------------------
192
193 // log everything to a "FILE *", stderr by default
194 class WXDLLEXPORT wxLogStderr : public wxLog
195 {
196 public:
197 // redirect log output to a FILE
198 wxLogStderr(FILE *fp = (FILE *) NULL);
199
200 private:
201 // implement sink function
202 virtual void DoLogString(const wxChar *szString, time_t t);
203
204 FILE *m_fp;
205 };
206
207 #if wxUSE_STD_IOSTREAM
208 // log everything to an "ostream", cerr by default
209 class WXDLLEXPORT wxLogStream : public wxLog
210 {
211 public:
212 // redirect log output to an ostream
213 wxLogStream(ostream *ostr = (ostream *) NULL);
214
215 protected:
216 // implement sink function
217 virtual void DoLogString(const wxChar *szString, time_t t);
218
219 // using ptr here to avoid including <iostream.h> from this file
220 ostream *m_ostr;
221 };
222 #endif
223
224 #ifndef wxUSE_NOGUI
225
226 #if wxUSE_STD_IOSTREAM
227 // log everything to a text window (GUI only of course)
228 class WXDLLEXPORT wxLogTextCtrl : public wxLogStream
229 {
230 public:
231 // we just create an ostream from wxTextCtrl and use it in base class
232 wxLogTextCtrl(wxTextCtrl *pTextCtrl);
233 ~wxLogTextCtrl();
234 };
235 #endif
236
237 // ----------------------------------------------------------------------------
238 // GUI log target, the default one for wxWindows programs
239 // ----------------------------------------------------------------------------
240 class WXDLLEXPORT wxLogGui : public wxLog
241 {
242 public:
243 // ctor
244 wxLogGui();
245
246 // show all messages that were logged since the last Flush()
247 virtual void Flush();
248
249 protected:
250 virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t);
251
252 // empty everything
253 void Clear();
254
255 wxArrayString m_aMessages;
256 wxArrayLong m_aTimes;
257 bool m_bErrors, // do we have any errors?
258 m_bWarnings; // any warnings?
259 };
260
261 // ----------------------------------------------------------------------------
262 // (background) log window: this class forwards all log messages to the log
263 // target which was active when it was instantiated, but also collects them
264 // to the log window. This window has it's own menu which allows the user to
265 // close it, clear the log contents or save it to the file.
266 // ----------------------------------------------------------------------------
267 class WXDLLEXPORT wxLogWindow : public wxLog
268 {
269 public:
270 wxLogWindow(wxFrame *pParent, // the parent frame (can be NULL)
271 const wxChar *szTitle, // the title of the frame
272 bool bShow = TRUE, // show window immediately?
273 bool bPassToOld = TRUE); // pass log messages to the old target?
274 ~wxLogWindow();
275
276 // window operations
277 // show/hide the log window
278 void Show(bool bShow = TRUE);
279 // retrieve the pointer to the frame
280 wxFrame *GetFrame() const;
281
282 // accessors
283 // the previous log target (may be NULL)
284 wxLog *GetOldLog() const { return m_pOldLog; }
285 // are we passing the messages to the previous log target?
286 bool IsPassingMessages() const { return m_bPassMessages; }
287
288 // we can pass the messages to the previous log target (we're in this mode by
289 // default: we collect all messages in the window, but also let the default
290 // processing take place)
291 void PassMessages(bool bDoPass) { m_bPassMessages = bDoPass; }
292
293 // base class virtuals
294 // we don't need it ourselves, but we pass it to the previous logger
295 virtual void Flush();
296
297 // overridables
298 // called immediately after the log frame creation allowing for
299 // any extra initializations
300 virtual void OnFrameCreate(wxFrame *frame);
301 // called right before the log frame is going to be deleted
302 virtual void OnFrameDelete(wxFrame *frame);
303
304 protected:
305 virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t);
306 virtual void DoLogString(const wxChar *szString, time_t t);
307
308 private:
309 bool m_bPassMessages; // pass messages to m_pOldLog?
310 wxLog *m_pOldLog; // previous log target
311 wxLogFrame *m_pLogFrame; // the log frame
312 };
313
314 #endif // wxUSE_NOGUI
315
316 // ----------------------------------------------------------------------------
317 // /dev/null log target: suppress logging until this object goes out of scope
318 // ----------------------------------------------------------------------------
319
320 // example of usage:
321 /*
322 void Foo() {
323 wxFile file;
324
325 // wxFile.Open() normally complains if file can't be opened, we don't want it
326 wxLogNull logNo;
327 if ( !file.Open("bar") )
328 ... process error ourselves ...
329
330 // ~wxLogNull called, old log sink restored
331 }
332 */
333 class WXDLLEXPORT wxLogNull
334 {
335 public:
336 wxLogNull() { m_flagOld = wxLog::EnableLogging(FALSE); }
337 ~wxLogNull() { (void)wxLog::EnableLogging(m_flagOld); }
338
339 private:
340 bool m_flagOld; // the previous value of the wxLog::ms_doLog
341 };
342
343 // ============================================================================
344 // global functions
345 // ============================================================================
346
347 // ----------------------------------------------------------------------------
348 // Log functions should be used by application instead of stdio, iostream &c
349 // for log messages for easy redirection
350 // ----------------------------------------------------------------------------
351
352 // are we in 'verbose' mode?
353 // (note that it's often handy to change this var manually from the
354 // debugger, thus enabling/disabling verbose reporting for some
355 // parts of the program only)
356 WXDLLEXPORT_DATA(extern bool) g_bVerbose;
357
358 // ----------------------------------------------------------------------------
359 // get error code/error message from system in a portable way
360 // ----------------------------------------------------------------------------
361
362 // return the last system error code
363 WXDLLEXPORT unsigned long wxSysErrorCode();
364 // return the error message for given (or last if 0) error code
365 WXDLLEXPORT const wxChar* wxSysErrorMsg(unsigned long nErrCode = 0);
366
367 // define wxLog<level>
368 // -------------------
369
370 #define DECLARE_LOG_FUNCTION(level) \
371 extern void WXDLLEXPORT wxLog##level(const wxChar *szFormat, ...)
372 #define DECLARE_LOG_FUNCTION2(level, arg1) \
373 extern void WXDLLEXPORT wxLog##level(arg1, const wxChar *szFormat, ...)
374
375 #else // !wxUSE_LOG
376
377 // log functions do nothing at all
378 #define DECLARE_LOG_FUNCTION(level) \
379 inline void WXDLLEXPORT wxLog##level(const wxChar * WXUNUSED(szFormat), ...) {}
380 #define DECLARE_LOG_FUNCTION2(level, arg1) \
381 inline void WXDLLEXPORT wxLog##level(WXUNUSED(arg1), \
382 const wxChar *WXUNUSED(szFormat), ...) {}
383
384 #endif // wxUSE_LOG/!wxUSE_LOG
385
386 // a generic function for all levels (level is passes as parameter)
387 DECLARE_LOG_FUNCTION2(Generic, wxLogLevel level);
388
389 // one function per each level
390 DECLARE_LOG_FUNCTION(FatalError);
391 DECLARE_LOG_FUNCTION(Error);
392 DECLARE_LOG_FUNCTION(Warning);
393 DECLARE_LOG_FUNCTION(Message);
394 DECLARE_LOG_FUNCTION(Info);
395 DECLARE_LOG_FUNCTION(Verbose);
396
397 // this function sends the log message to the status line of the top level
398 // application frame, if any
399 DECLARE_LOG_FUNCTION(Status);
400
401 // this one is the same as previous except that it allows to explicitly
402 // specify the frame to which the output should go
403 DECLARE_LOG_FUNCTION2(Status, wxFrame *pFrame);
404
405 // additional one: as wxLogError, but also logs last system call error code
406 // and the corresponding error message if available
407 DECLARE_LOG_FUNCTION(SysError);
408
409 // and another one which also takes the error code (for those broken APIs
410 // that don't set the errno (like registry APIs in Win32))
411 DECLARE_LOG_FUNCTION2(SysError, long lErrCode);
412
413 // debug functions do nothing in release mode
414 #ifdef __WXDEBUG__
415 DECLARE_LOG_FUNCTION(Debug);
416
417 // first king of LogTrace is uncoditional: it doesn't check the level,
418 DECLARE_LOG_FUNCTION(Trace);
419
420 // this second version will only log the message if the mask had been
421 // added to the list of masks with AddTraceMask()
422 DECLARE_LOG_FUNCTION2(Trace, const char *mask);
423
424 // the last one does nothing if all of level bits are not set
425 // in wxLog::GetActive()->GetTraceMask() - it's deprecated in favour of
426 // string identifiers
427 DECLARE_LOG_FUNCTION2(Trace, wxTraceMask mask);
428 #else //!debug
429 // these functions do nothing in release builds
430 inline void wxLogDebug(const wxChar *, ...) { }
431 inline void wxLogTrace(const wxChar *, ...) { }
432 inline void wxLogTrace(wxTraceMask, const wxChar *, ...) { }
433 inline void wxLogTrace(const wxChar *, const wxChar *, ...) { }
434 #endif // debug/!debug
435
436 // ----------------------------------------------------------------------------
437 // debug only logging functions: use them with API name and error code
438 // ----------------------------------------------------------------------------
439
440 #ifndef __TFILE__
441 #define __XFILE__(x) _T(x)
442 #define __TFILE__ __XFILE__(__FILE__)
443 #endif
444
445 #if __WXDEBUG__
446 // make life easier for people using VC++ IDE: clicking on the message
447 // will take us immediately to the place of the failed API
448 #ifdef __VISUALC__
449 #define wxLogApiError(api, rc) \
450 wxLogDebug(_T("%s(%d): '%s' failed with error 0x%08lx (%s)."), \
451 __TFILE__, __LINE__, api, \
452 rc, wxSysErrorMsg(rc))
453 #else // !VC++
454 #define wxLogApiError(api, rc) \
455 wxLogDebug(_T("In file %s at line %d: '%s' failed with " \
456 "error 0x%08lx (%s)."), \
457 __TFILE__, __LINE__, api, \
458 rc, wxSysErrorMsg(rc))
459 #endif // VC++/!VC++
460
461 #define wxLogLastError(api) wxLogApiError(api, wxSysErrorCode())
462
463 #else //!debug
464 inline void wxLogApiError(const wxChar *, long) { }
465 inline void wxLogLastError(const wxChar *) { }
466 #endif //debug/!debug
467
468 #endif // _WX_LOG_H_