]> git.saurik.com Git - wxWidgets.git/blob - include/wx/log.h
fixed wxALL_FILES definition in Unicode build
[wxWidgets.git] / include / wx / log.h
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: wx/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 #if defined(__GNUG__) && !defined(__APPLE__)
16 #pragma interface "log.h"
17 #endif
18
19 #include "wx/setup.h"
20 #include "wx/string.h"
21
22 // ----------------------------------------------------------------------------
23 // forward declarations
24 // ----------------------------------------------------------------------------
25
26 class WXDLLEXPORT wxTextCtrl;
27 class WXDLLEXPORT wxLogFrame;
28 class WXDLLEXPORT wxFrame;
29
30 // ----------------------------------------------------------------------------
31 // types
32 // ----------------------------------------------------------------------------
33
34 typedef unsigned long wxTraceMask;
35 typedef unsigned long wxLogLevel;
36
37 // ----------------------------------------------------------------------------
38 // headers
39 // ----------------------------------------------------------------------------
40
41 #if wxUSE_LOG
42
43 #ifndef __WXWINCE__
44 #include <time.h> // for time_t
45 #endif
46
47 #include "wx/dynarray.h"
48
49 // ----------------------------------------------------------------------------
50 // constants
51 // ----------------------------------------------------------------------------
52
53 // different standard log levels (you may also define your own)
54 enum
55 {
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
66 };
67
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()
71
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
76
77 #ifdef __WXMSW__
78 #define wxTRACE_OleCalls wxT("ole") // OLE interface calls
79 #endif
80
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
83
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
90
91 #ifdef __WXMSW__
92 #define wxTraceOleCalls 0x0100 // OLE interface calls
93 #endif
94
95 #include "wx/ioswrap.h"
96
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 // ----------------------------------------------------------------------------
101
102 class WXDLLEXPORT wxLog
103 {
104 public:
105 // ctor
106 wxLog();
107
108 // Internal buffer.
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 );
113
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; }
120
121 // static sink function - see DoLog() for function to overload in the
122 // derived classes
123 static void OnLog(wxLogLevel level, const wxChar *szString, time_t t)
124 {
125 if ( IsEnabled() ) {
126 wxLog *pLogger = GetActiveTarget();
127 if ( pLogger )
128 pLogger->DoLog(level, szString, t);
129 }
130 }
131
132 // message buffering
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; }
141
142 // only one sink is active at each moment
143 // flush the active target if any
144 static void FlushActive()
145 {
146 if ( !ms_suspendCount )
147 {
148 wxLog *log = GetActiveTarget();
149 if ( log && log->HasPendingMessages() )
150 log->Flush();
151 }
152 }
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);
158
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--; }
165
166 // functions controlling the default wxLog behaviour
167 // verbose mode is activated by standard command-line '-verbose'
168 // option
169 static void SetVerbose(bool bVerbose = TRUE) { ms_bVerbose = bVerbose; }
170 // should GetActiveTarget() try to create a new log object if the
171 // current is NULL?
172 static void DontCreateOnDemand();
173
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; }
184
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; }
189
190 // accessors
191 // gets the verbose status
192 static bool GetVerbose() { return ms_bVerbose; }
193 // get trace mask
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; }
198
199 // get the current timestamp format string (may be NULL)
200 static const wxChar *GetTimestamp() { return ms_timestamp; }
201
202 // helpers
203 // put the time stamp into the string if ms_timestamp != NULL (don't
204 // change it otherwise)
205 static void TimeStamp(wxString *str);
206
207 // make dtor virtual for all derived classes
208 virtual ~wxLog() { }
209
210 protected:
211 bool m_bHasMessages; // any messages in the queue?
212
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);
220
221 private:
222 // static variables
223 // ----------------
224
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
229
230 static size_t ms_suspendCount; // if positive, logs are not flushed
231
232 // format string for strftime(), if NULL, time stamping log messages is
233 // disabled
234 static const wxChar *ms_timestamp;
235
236 static wxTraceMask ms_ulTraceMask; // controls wxLogTrace behaviour
237 static wxArrayString ms_aTraceMasks; // more powerful filter for wxLogTrace
238 };
239
240 // ----------------------------------------------------------------------------
241 // "trivial" derivations of wxLog
242 // ----------------------------------------------------------------------------
243
244 // log everything to a "FILE *", stderr by default
245 class WXDLLEXPORT wxLogStderr : public wxLog
246 {
247 DECLARE_NO_COPY_CLASS(wxLogStderr)
248
249 public:
250 // redirect log output to a FILE
251 wxLogStderr(FILE *fp = (FILE *) NULL);
252
253 protected:
254 // implement sink function
255 virtual void DoLogString(const wxChar *szString, time_t t);
256
257 FILE *m_fp;
258 };
259
260 #if wxUSE_STD_IOSTREAM
261
262 // log everything to an "ostream", cerr by default
263 class WXDLLEXPORT wxLogStream : public wxLog
264 {
265 public:
266 // redirect log output to an ostream
267 wxLogStream(wxSTD ostream *ostr = (wxSTD ostream *) NULL);
268
269 protected:
270 // implement sink function
271 virtual void DoLogString(const wxChar *szString, time_t t);
272
273 // using ptr here to avoid including <iostream.h> from this file
274 wxSTD ostream *m_ostr;
275 };
276
277 #endif // wxUSE_STD_IOSTREAM
278
279 // ----------------------------------------------------------------------------
280 // /dev/null log target: suppress logging until this object goes out of scope
281 // ----------------------------------------------------------------------------
282
283 // example of usage:
284 /*
285 void Foo()
286 {
287 wxFile file;
288
289 // wxFile.Open() normally complains if file can't be opened, we don't
290 // want it
291 wxLogNull logNo;
292
293 if ( !file.Open("bar") )
294 ... process error ourselves ...
295
296 // ~wxLogNull called, old log sink restored
297 }
298 */
299 class WXDLLEXPORT wxLogNull
300 {
301 public:
302 wxLogNull() : m_flagOld(wxLog::EnableLogging(FALSE)) { }
303 ~wxLogNull() { (void)wxLog::EnableLogging(m_flagOld); }
304
305 private:
306 bool m_flagOld; // the previous value of the wxLog::ms_doLog
307 };
308
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
313 //
314 // note that you don't have to call SetActiveTarget() with this class, it
315 // does it itself in its ctor
316 // ----------------------------------------------------------------------------
317
318 class WXDLLEXPORT wxLogChain : public wxLog
319 {
320 public:
321 wxLogChain(wxLog *logger);
322 virtual ~wxLogChain();
323
324 // change the new log target
325 void SetLog(wxLog *logger);
326
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; }
330
331 // are we passing the messages to the previous log target?
332 bool IsPassingMessages() const { return m_bPassMessages; }
333
334 // return the previous log target (may be NULL)
335 wxLog *GetOldLog() const { return m_logOld; }
336
337 // override base class version to flush the old logger as well
338 virtual void Flush();
339
340 protected:
341 // pass the chain to the old logger if needed
342 virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t);
343
344 private:
345 // the current log target
346 wxLog *m_logNew;
347
348 // the previous log target
349 wxLog *m_logOld;
350
351 // do we pass the messages to the old logger?
352 bool m_bPassMessages;
353 };
354
355 // a chain log target which uses itself as the new logger
356 class WXDLLEXPORT wxLogPassThrough : public wxLogChain
357 {
358 public:
359 wxLogPassThrough();
360 };
361
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 // ----------------------------------------------------------------------------
367
368 #if wxUSE_GUI
369
370 #if wxUSE_TEXTCTRL
371
372 // log everything to a text window (GUI only of course)
373 class WXDLLEXPORT wxLogTextCtrl : public wxLog
374 {
375 public:
376 wxLogTextCtrl(wxTextCtrl *pTextCtrl);
377
378 private:
379 // implement sink function
380 virtual void DoLogString(const wxChar *szString, time_t t);
381
382 // the control we use
383 wxTextCtrl *m_pTextCtrl;
384 };
385
386 #endif // wxUSE_TEXTCTRL
387
388 // ----------------------------------------------------------------------------
389 // GUI log target, the default one for wxWindows programs
390 // ----------------------------------------------------------------------------
391
392 #if wxUSE_LOGGUI
393
394 class WXDLLEXPORT wxLogGui : public wxLog
395 {
396 public:
397 // ctor
398 wxLogGui();
399
400 // show all messages that were logged since the last Flush()
401 virtual void Flush();
402
403 protected:
404 virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t);
405
406 // empty everything
407 void Clear();
408
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?
414 };
415
416 #endif // wxUSE_LOGGUI
417
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 // ----------------------------------------------------------------------------
424
425 #if wxUSE_LOGWINDOW
426
427 class WXDLLEXPORT wxLogWindow : public wxLogPassThrough
428 {
429 public:
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?
434
435 ~wxLogWindow();
436
437 // window operations
438 // show/hide the log window
439 void Show(bool bShow = TRUE);
440 // retrieve the pointer to the frame
441 wxFrame *GetFrame() const;
442
443 // overridables
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);
455
456 protected:
457 virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t);
458 virtual void DoLogString(const wxChar *szString, time_t t);
459
460 private:
461 wxLogFrame *m_pLogFrame; // the log frame
462 };
463
464 #endif // wxUSE_LOGWINDOW
465
466 #endif // wxUSE_GUI
467
468 // ============================================================================
469 // global functions
470 // ============================================================================
471
472 // ----------------------------------------------------------------------------
473 // Log functions should be used by application instead of stdio, iostream &c
474 // for log messages for easy redirection
475 // ----------------------------------------------------------------------------
476
477 // ----------------------------------------------------------------------------
478 // get error code/error message from system in a portable way
479 // ----------------------------------------------------------------------------
480
481 // return the last system error code
482 WXDLLEXPORT unsigned long wxSysErrorCode();
483
484 // return the error message for given (or last if 0) error code
485 WXDLLEXPORT const wxChar* wxSysErrorMsg(unsigned long nErrCode = 0);
486
487 // ----------------------------------------------------------------------------
488 // define wxLog<level>
489 // ----------------------------------------------------------------------------
490
491 #define DECLARE_LOG_FUNCTION(level) \
492 extern void WXDLLEXPORT wxVLog##level(const wxChar *szFormat, \
493 va_list argptr); \
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, \
498 va_list argptr); \
499 extern void WXDLLEXPORT wxLog##level(arg1, const wxChar *szFormat, \
500 ...) ATTRIBUTE_PRINTF_2
501
502 #else // !wxUSE_LOG
503
504 // log functions do nothing at all
505 #define DECLARE_LOG_FUNCTION(level) \
506 inline void WXDLLEXPORT wxVLog##level(const wxChar *szFormat, \
507 va_list argptr) {} \
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, \
511 va_list argptr) {} \
512 inline void WXDLLEXPORT wxLog##level(arg1, const wxChar *szFormat, ...) {}
513
514 #endif // wxUSE_LOG/!wxUSE_LOG
515
516 // a generic function for all levels (level is passes as parameter)
517 DECLARE_LOG_FUNCTION2(Generic, wxLogLevel level);
518
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);
526
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);
530
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);
534
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);
538
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);
542
543 // debug functions do nothing in release mode
544 #ifdef __WXDEBUG__
545 DECLARE_LOG_FUNCTION(Debug);
546
547 // first kind of LogTrace is unconditional: it doesn't check the level,
548 DECLARE_LOG_FUNCTION(Trace);
549
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);
553
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);
558 #else //!debug
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
569
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);
573
574 // ----------------------------------------------------------------------------
575 // debug only logging functions: use them with API name and error code
576 // ----------------------------------------------------------------------------
577
578 #ifdef __WXDEBUG__
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
581 #ifdef __VISUALC__
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))
586 #else // !VC++
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))
592 #endif // VC++/!VC++
593
594 #define wxLogLastError(api) wxLogApiError(api, wxSysErrorCode())
595
596 #else //!debug
597 inline void wxLogApiError(const wxChar *, long) { }
598 inline void wxLogLastError(const wxChar *) { }
599 #endif //debug/!debug
600
601 #endif // _WX_LOG_H_
602
603 // vi:sts=4:sw=4:et