]> git.saurik.com Git - wxWidgets.git/blame_incremental - include/wx/log.h
Apply patch [ 1548750 ] wxVsnprintf() various fixes
[wxWidgets.git] / include / wx / log.h
... / ...
CommitLineData
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 licence
10/////////////////////////////////////////////////////////////////////////////
11
12#ifndef _WX_LOG_H_
13#define _WX_LOG_H_
14
15#include "wx/defs.h"
16
17// ----------------------------------------------------------------------------
18// common constants for use in wxUSE_LOG/!wxUSE_LOG
19// ----------------------------------------------------------------------------
20
21// the trace masks have been superceded by symbolic trace constants, they're
22// for compatibility only andwill be removed soon - do NOT use them
23
24// meaning of different bits of the trace mask (which allows selectively
25// enable/disable some trace messages)
26#define wxTraceMemAlloc 0x0001 // trace memory allocation (new/delete)
27#define wxTraceMessages 0x0002 // trace window messages/X callbacks
28#define wxTraceResAlloc 0x0004 // trace GDI resource allocation
29#define wxTraceRefCount 0x0008 // trace various ref counting operations
30
31#ifdef __WXMSW__
32 #define wxTraceOleCalls 0x0100 // OLE interface calls
33#endif
34
35// ----------------------------------------------------------------------------
36// types
37// ----------------------------------------------------------------------------
38
39// NB: these types are needed even if wxUSE_LOG == 0
40typedef unsigned long wxTraceMask;
41typedef unsigned long wxLogLevel;
42
43// ----------------------------------------------------------------------------
44// headers
45// ----------------------------------------------------------------------------
46
47#include "wx/string.h"
48
49#if wxUSE_LOG
50
51#include "wx/arrstr.h"
52
53#ifndef __WXWINCE__
54 #include <time.h> // for time_t
55#endif
56
57#include "wx/dynarray.h"
58
59#ifndef wxUSE_LOG_DEBUG
60# ifdef __WXDEBUG__
61# define wxUSE_LOG_DEBUG 1
62# else // !__WXDEBUG__
63# define wxUSE_LOG_DEBUG 0
64# endif
65#endif
66
67// ----------------------------------------------------------------------------
68// forward declarations
69// ----------------------------------------------------------------------------
70
71#if wxUSE_GUI
72 class WXDLLIMPEXP_CORE wxTextCtrl;
73 class WXDLLIMPEXP_CORE wxLogFrame;
74 class WXDLLIMPEXP_CORE wxFrame;
75 class WXDLLIMPEXP_CORE wxWindow;
76#endif // wxUSE_GUI
77
78// ----------------------------------------------------------------------------
79// constants
80// ----------------------------------------------------------------------------
81
82// different standard log levels (you may also define your own)
83enum
84{
85 wxLOG_FatalError, // program can't continue, abort immediately
86 wxLOG_Error, // a serious error, user must be informed about it
87 wxLOG_Warning, // user is normally informed about it but may be ignored
88 wxLOG_Message, // normal message (i.e. normal output of a non GUI app)
89 wxLOG_Status, // informational: might go to the status line of GUI app
90 wxLOG_Info, // informational message (a.k.a. 'Verbose')
91 wxLOG_Debug, // never shown to the user, disabled in release mode
92 wxLOG_Trace, // trace messages are also only enabled in debug mode
93 wxLOG_Progress, // used for progress indicator (not yet)
94 wxLOG_User = 100, // user defined levels start here
95 wxLOG_Max = 10000
96};
97
98// symbolic trace masks - wxLogTrace("foo", "some trace message...") will be
99// discarded unless the string "foo" has been added to the list of allowed
100// ones with AddTraceMask()
101
102#define wxTRACE_MemAlloc wxT("memalloc") // trace memory allocation (new/delete)
103#define wxTRACE_Messages wxT("messages") // trace window messages/X callbacks
104#define wxTRACE_ResAlloc wxT("resalloc") // trace GDI resource allocation
105#define wxTRACE_RefCount wxT("refcount") // trace various ref counting operations
106
107#ifdef __WXMSW__
108 #define wxTRACE_OleCalls wxT("ole") // OLE interface calls
109#endif
110
111#include "wx/iosfwrap.h"
112
113// ----------------------------------------------------------------------------
114// derive from this class to redirect (or suppress, or ...) log messages
115// normally, only a single instance of this class exists but it's not enforced
116// ----------------------------------------------------------------------------
117
118class WXDLLIMPEXP_BASE wxLog
119{
120public:
121 // ctor
122 wxLog(){}
123
124 // these functions allow to completely disable all log messages
125
126 // is logging disabled now?
127 static bool IsEnabled() { return ms_doLog; }
128
129 // change the flag state, return the previous one
130 static bool EnableLogging(bool doIt = true)
131 { bool doLogOld = ms_doLog; ms_doLog = doIt; return doLogOld; }
132
133 // static sink function - see DoLog() for function to overload in the
134 // derived classes
135 static void OnLog(wxLogLevel level, const wxChar *szString, time_t t);
136
137 // message buffering
138
139 // flush shows all messages if they're not logged immediately (FILE
140 // and iostream logs don't need it, but wxGuiLog does to avoid showing
141 // 17 modal dialogs one after another)
142 virtual void Flush();
143
144 // flush the active target if any
145 static void FlushActive()
146 {
147 if ( !ms_suspendCount )
148 {
149 wxLog *log = GetActiveTarget();
150 if ( log )
151 log->Flush();
152 }
153 }
154
155 // only one sink is active at each moment
156 // get current log target, will call wxApp::CreateLogTarget() to
157 // create one if none exists
158 static wxLog *GetActiveTarget();
159
160 // change log target, pLogger may be NULL
161 static wxLog *SetActiveTarget(wxLog *pLogger);
162
163 // suspend the message flushing of the main target until the next call
164 // to Resume() - this is mainly for internal use (to prevent wxYield()
165 // from flashing the messages)
166 static void Suspend() { ms_suspendCount++; }
167
168 // must be called for each Suspend()!
169 static void Resume() { ms_suspendCount--; }
170
171 // functions controlling the default wxLog behaviour
172 // verbose mode is activated by standard command-line '-verbose'
173 // option
174 static void SetVerbose(bool bVerbose = true) { ms_bVerbose = bVerbose; }
175
176 // Set log level. Log messages with level > logLevel will not be logged.
177 static void SetLogLevel(wxLogLevel logLevel) { ms_logLevel = logLevel; }
178
179 // should GetActiveTarget() try to create a new log object if the
180 // current is NULL?
181 static void DontCreateOnDemand();
182
183 // log the count of repeating messages instead of logging the messages
184 // multiple times
185 static void SetRepetitionCounting(bool bRepetCounting = true)
186 { ms_bRepetCounting = bRepetCounting; }
187
188 // gets duplicate counting status
189 static bool GetRepetitionCounting() { return ms_bRepetCounting; }
190
191 // trace mask (see wxTraceXXX constants for details)
192 static void SetTraceMask(wxTraceMask ulMask) { ms_ulTraceMask = ulMask; }
193
194 // add string trace mask
195 static void AddTraceMask(const wxString& str)
196 { ms_aTraceMasks.push_back(str); }
197
198 // add string trace mask
199 static void RemoveTraceMask(const wxString& str);
200
201 // remove all string trace masks
202 static void ClearTraceMasks();
203
204 // get string trace masks
205 static const wxArrayString &GetTraceMasks() { return ms_aTraceMasks; }
206
207 // sets the timestamp string: this is used as strftime() format string
208 // for the log targets which add time stamps to the messages - set it
209 // to NULL to disable time stamping completely.
210 static void SetTimestamp(const wxChar *ts) { ms_timestamp = ts; }
211
212
213 // accessors
214
215 // gets the verbose status
216 static bool GetVerbose() { return ms_bVerbose; }
217
218 // get trace mask
219 static wxTraceMask GetTraceMask() { return ms_ulTraceMask; }
220
221 // is this trace mask in the list?
222 static bool IsAllowedTraceMask(const wxChar *mask);
223
224 // return the current loglevel limit
225 static wxLogLevel GetLogLevel() { return ms_logLevel; }
226
227 // get the current timestamp format string (may be NULL)
228 static const wxChar *GetTimestamp() { return ms_timestamp; }
229
230
231 // helpers
232
233 // put the time stamp into the string if ms_timestamp != NULL (don't
234 // change it otherwise)
235 static void TimeStamp(wxString *str);
236
237 // make dtor virtual for all derived classes
238 virtual ~wxLog();
239
240
241 // this method exists for backwards compatibility only, don't use
242 bool HasPendingMessages() const { return true; }
243
244#if WXWIN_COMPATIBILITY_2_6
245 // this function doesn't do anything any more, don't call it
246 wxDEPRECATED( static wxChar *SetLogBuffer(wxChar *buf, size_t size = 0) );
247#endif
248
249protected:
250 // the logging functions that can be overriden
251
252 // default DoLog() prepends the time stamp and a prefix corresponding
253 // to the message to szString and then passes it to DoLogString()
254 virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t);
255
256 // default DoLogString does nothing but is not pure virtual because if
257 // you override DoLog() you might not need it at all
258 virtual void DoLogString(const wxChar *szString, time_t t);
259
260 // log a line containing the number of times the previous message was
261 // repeated
262 // returns: the number
263 static unsigned DoLogNumberOfRepeats();
264
265private:
266 // static variables
267 // ----------------
268
269 // traditional behaviour or counting repetitions
270 static bool ms_bRepetCounting;
271 static wxString ms_prevString; // previous message that was logged
272 // how many times the previous message was logged
273 static unsigned ms_prevCounter;
274 static time_t ms_prevTimeStamp;// timestamp of the previous message
275 static wxLogLevel ms_prevLevel; // level of the previous message
276
277 static wxLog *ms_pLogger; // currently active log sink
278 static bool ms_doLog; // false => all logging disabled
279 static bool ms_bAutoCreate; // create new log targets on demand?
280 static bool ms_bVerbose; // false => ignore LogInfo messages
281
282 static wxLogLevel ms_logLevel; // limit logging to levels <= ms_logLevel
283
284 static size_t ms_suspendCount; // if positive, logs are not flushed
285
286 // format string for strftime(), if NULL, time stamping log messages is
287 // disabled
288 static const wxChar *ms_timestamp;
289
290 static wxTraceMask ms_ulTraceMask; // controls wxLogTrace behaviour
291 static wxArrayString ms_aTraceMasks; // more powerful filter for wxLogTrace
292};
293
294// ----------------------------------------------------------------------------
295// "trivial" derivations of wxLog
296// ----------------------------------------------------------------------------
297
298// log everything to a buffer
299class WXDLLIMPEXP_BASE wxLogBuffer : public wxLog
300{
301public:
302 wxLogBuffer() { }
303
304 // get the string contents with all messages logged
305 const wxString& GetBuffer() const { return m_str; }
306
307 // show the buffer contents to the user in the best possible way (this uses
308 // wxMessageOutputMessageBox) and clear it
309 virtual void Flush();
310
311protected:
312 virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t);
313 virtual void DoLogString(const wxChar *szString, time_t t);
314
315private:
316 wxString m_str;
317
318 DECLARE_NO_COPY_CLASS(wxLogBuffer)
319};
320
321
322// log everything to a "FILE *", stderr by default
323class WXDLLIMPEXP_BASE wxLogStderr : public wxLog
324{
325public:
326 // redirect log output to a FILE
327 wxLogStderr(FILE *fp = (FILE *) NULL);
328
329protected:
330 // implement sink function
331 virtual void DoLogString(const wxChar *szString, time_t t);
332
333 FILE *m_fp;
334
335 DECLARE_NO_COPY_CLASS(wxLogStderr)
336};
337
338#if wxUSE_STD_IOSTREAM
339
340// log everything to an "ostream", cerr by default
341class WXDLLIMPEXP_BASE wxLogStream : public wxLog
342{
343public:
344 // redirect log output to an ostream
345 wxLogStream(wxSTD ostream *ostr = (wxSTD ostream *) NULL);
346
347protected:
348 // implement sink function
349 virtual void DoLogString(const wxChar *szString, time_t t);
350
351 // using ptr here to avoid including <iostream.h> from this file
352 wxSTD ostream *m_ostr;
353};
354
355#endif // wxUSE_STD_IOSTREAM
356
357// ----------------------------------------------------------------------------
358// /dev/null log target: suppress logging until this object goes out of scope
359// ----------------------------------------------------------------------------
360
361// example of usage:
362/*
363 void Foo()
364 {
365 wxFile file;
366
367 // wxFile.Open() normally complains if file can't be opened, we don't
368 // want it
369 wxLogNull logNo;
370
371 if ( !file.Open("bar") )
372 ... process error ourselves ...
373
374 // ~wxLogNull called, old log sink restored
375 }
376 */
377class WXDLLIMPEXP_BASE wxLogNull
378{
379public:
380 wxLogNull() : m_flagOld(wxLog::EnableLogging(false)) { }
381 ~wxLogNull() { (void)wxLog::EnableLogging(m_flagOld); }
382
383private:
384 bool m_flagOld; // the previous value of the wxLog::ms_doLog
385};
386
387// ----------------------------------------------------------------------------
388// chaining log target: installs itself as a log target and passes all
389// messages to the real log target given to it in the ctor but also forwards
390// them to the previously active one
391//
392// note that you don't have to call SetActiveTarget() with this class, it
393// does it itself in its ctor
394// ----------------------------------------------------------------------------
395
396class WXDLLIMPEXP_BASE wxLogChain : public wxLog
397{
398public:
399 wxLogChain(wxLog *logger);
400 virtual ~wxLogChain();
401
402 // change the new log target
403 void SetLog(wxLog *logger);
404
405 // this can be used to temporarily disable (and then reenable) passing
406 // messages to the old logger (by default we do pass them)
407 void PassMessages(bool bDoPass) { m_bPassMessages = bDoPass; }
408
409 // are we passing the messages to the previous log target?
410 bool IsPassingMessages() const { return m_bPassMessages; }
411
412 // return the previous log target (may be NULL)
413 wxLog *GetOldLog() const { return m_logOld; }
414
415 // override base class version to flush the old logger as well
416 virtual void Flush();
417
418protected:
419 // pass the chain to the old logger if needed
420 virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t);
421
422private:
423 // the current log target
424 wxLog *m_logNew;
425
426 // the previous log target
427 wxLog *m_logOld;
428
429 // do we pass the messages to the old logger?
430 bool m_bPassMessages;
431
432 DECLARE_NO_COPY_CLASS(wxLogChain)
433};
434
435// a chain log target which uses itself as the new logger
436class WXDLLIMPEXP_BASE wxLogPassThrough : public wxLogChain
437{
438public:
439 wxLogPassThrough();
440
441private:
442 DECLARE_NO_COPY_CLASS(wxLogPassThrough)
443};
444
445#if wxUSE_GUI
446 // include GUI log targets:
447 #include "wx/generic/logg.h"
448#endif // wxUSE_GUI
449
450// ============================================================================
451// global functions
452// ============================================================================
453
454// ----------------------------------------------------------------------------
455// Log functions should be used by application instead of stdio, iostream &c
456// for log messages for easy redirection
457// ----------------------------------------------------------------------------
458
459// ----------------------------------------------------------------------------
460// get error code/error message from system in a portable way
461// ----------------------------------------------------------------------------
462
463// return the last system error code
464WXDLLIMPEXP_BASE unsigned long wxSysErrorCode();
465
466// return the error message for given (or last if 0) error code
467WXDLLIMPEXP_BASE const wxChar* wxSysErrorMsg(unsigned long nErrCode = 0);
468
469// ----------------------------------------------------------------------------
470// define wxLog<level>
471// ----------------------------------------------------------------------------
472
473#define DECLARE_LOG_FUNCTION(level) \
474extern void WXDLLIMPEXP_BASE wxVLog##level(const wxChar *szFormat, \
475 va_list argptr); \
476extern void WXDLLIMPEXP_BASE wxLog##level(const wxChar *szFormat, \
477 ...) ATTRIBUTE_PRINTF_1
478#define DECLARE_LOG_FUNCTION2_EXP(level, argclass, arg, expdecl) \
479extern void expdecl wxVLog##level(argclass arg, \
480 const wxChar *szFormat, \
481 va_list argptr); \
482extern void expdecl wxLog##level(argclass arg, \
483 const wxChar *szFormat, \
484 ...) ATTRIBUTE_PRINTF_2
485#else // !wxUSE_LOG
486
487// log functions do nothing at all
488#define DECLARE_LOG_FUNCTION(level) \
489inline void wxVLog##level(const wxChar *WXUNUSED(szFormat), \
490 va_list WXUNUSED(argptr)) { } \
491inline void wxLog##level(const wxChar *WXUNUSED(szFormat), \
492 ...) { }
493#define DECLARE_LOG_FUNCTION2_EXP(level, argclass, arg, expdecl) \
494inline void wxVLog##level(argclass WXUNUSED(arg), \
495 const wxChar *WXUNUSED(szFormat), \
496 va_list WXUNUSED(argptr)) {} \
497inline void wxLog##level(argclass WXUNUSED(arg), \
498 const wxChar *WXUNUSED(szFormat), \
499 ...) { }
500
501// Empty Class to fake wxLogNull
502class WXDLLIMPEXP_BASE wxLogNull
503{
504public:
505 wxLogNull() { }
506};
507
508// Dummy macros to replace some functions.
509#define wxSysErrorCode() (unsigned long)0
510#define wxSysErrorMsg( X ) (const wxChar*)NULL
511
512// Fake symbolic trace masks... for those that are used frequently
513#define wxTRACE_OleCalls wxEmptyString // OLE interface calls
514
515#endif // wxUSE_LOG/!wxUSE_LOG
516
517#define DECLARE_LOG_FUNCTION2(level, argclass, arg) \
518 DECLARE_LOG_FUNCTION2_EXP(level, argclass, arg, WXDLLIMPEXP_BASE)
519
520
521// a generic function for all levels (level is passes as parameter)
522DECLARE_LOG_FUNCTION2(Generic, wxLogLevel, level);
523
524// one function per each level
525DECLARE_LOG_FUNCTION(FatalError);
526DECLARE_LOG_FUNCTION(Error);
527DECLARE_LOG_FUNCTION(Warning);
528DECLARE_LOG_FUNCTION(Message);
529DECLARE_LOG_FUNCTION(Info);
530DECLARE_LOG_FUNCTION(Verbose);
531
532// this function sends the log message to the status line of the top level
533// application frame, if any
534DECLARE_LOG_FUNCTION(Status);
535
536#if wxUSE_GUI
537 // this one is the same as previous except that it allows to explicitly
538 class WXDLLEXPORT wxFrame;
539 // specify the frame to which the output should go
540 DECLARE_LOG_FUNCTION2_EXP(Status, wxFrame *, pFrame, WXDLLIMPEXP_CORE);
541#endif // wxUSE_GUI
542
543// additional one: as wxLogError, but also logs last system call error code
544// and the corresponding error message if available
545DECLARE_LOG_FUNCTION(SysError);
546
547// and another one which also takes the error code (for those broken APIs
548// that don't set the errno (like registry APIs in Win32))
549DECLARE_LOG_FUNCTION2(SysError, long, lErrCode);
550
551// debug functions do nothing in release mode
552#if wxUSE_LOG && wxUSE_LOG_DEBUG
553 DECLARE_LOG_FUNCTION(Debug);
554
555 // there is no more unconditional LogTrace: it is not different from
556 // LogDebug and it creates overload ambiguities
557 //DECLARE_LOG_FUNCTION(Trace);
558
559 // this version only logs the message if the mask had been added to the
560 // list of masks with AddTraceMask()
561 DECLARE_LOG_FUNCTION2(Trace, const wxChar *, mask);
562
563 // and this one does nothing if all of level bits are not set in
564 // wxLog::GetActive()->GetTraceMask() -- it's deprecated in favour of
565 // string identifiers
566 DECLARE_LOG_FUNCTION2(Trace, wxTraceMask, mask);
567#else //!debug || !wxUSE_LOG
568 // these functions do nothing in release builds, but don't define them as
569 // nothing as it could result in different code structure in debug and
570 // release and this could result in trouble when these macros are used
571 // inside if/else
572 //
573 // note that making wxVLogDebug/Trace() themselves (empty inline) functions
574 // is a bad idea as some compilers are stupid enough to not inline even
575 // empty functions if their parameters are complicated enough, but by
576 // defining them as an empty inline function we ensure that even dumbest
577 // compilers optimise them away
578 inline void wxLogNop() { }
579
580 #define wxVLogDebug(fmt, valist) wxLogNop()
581 #define wxVLogTrace(mask, fmt, valist) wxLogNop()
582
583 #ifdef HAVE_VARIADIC_MACROS
584 // unlike the inline functions below, this completely removes the
585 // wxLogXXX calls from the object file:
586 #define wxLogDebug(fmt, ...) wxLogNop()
587 #define wxLogTrace(mask, fmt, ...) wxLogNop()
588 #else // !HAVE_VARIADIC_MACROS
589 // note that leaving out "fmt" in the vararg functions provokes a warning
590 // from SGI CC: "the last argument of the varargs function is unnamed"
591 inline void wxLogDebug(const wxChar *fmt, ...) { wxUnusedVar(fmt); }
592 inline void wxLogTrace(wxTraceMask, const wxChar *fmt, ...) { wxUnusedVar(fmt); }
593 inline void wxLogTrace(const wxChar *, const wxChar *fmt, ...) { wxUnusedVar(fmt); }
594 #endif // HAVE_VARIADIC_MACROS/!HAVE_VARIADIC_MACROS
595#endif // debug/!debug
596
597// wxLogFatalError helper: show the (fatal) error to the user in a safe way,
598// i.e. without using wxMessageBox() for example because it could crash
599void WXDLLIMPEXP_BASE
600wxSafeShowMessage(const wxString& title, const wxString& text);
601
602// ----------------------------------------------------------------------------
603// debug only logging functions: use them with API name and error code
604// ----------------------------------------------------------------------------
605
606#ifdef __WXDEBUG__
607 // make life easier for people using VC++ IDE: clicking on the message
608 // will take us immediately to the place of the failed API
609#ifdef __VISUALC__
610 #define wxLogApiError(api, rc) \
611 wxLogDebug(wxT("%s(%d): '%s' failed with error 0x%08lx (%s)."), \
612 __TFILE__, __LINE__, api, \
613 (long)rc, wxSysErrorMsg(rc))
614#else // !VC++
615 #define wxLogApiError(api, rc) \
616 wxLogDebug(wxT("In file %s at line %d: '%s' failed with ") \
617 wxT("error 0x%08lx (%s)."), \
618 __TFILE__, __LINE__, api, \
619 (long)rc, wxSysErrorMsg(rc))
620#endif // VC++/!VC++
621
622 #define wxLogLastError(api) wxLogApiError(api, wxSysErrorCode())
623
624#else //!debug
625 #define wxLogApiError(api, err) wxLogNop()
626 #define wxLogLastError(api) wxLogNop()
627#endif //debug/!debug
628
629// wxCocoa has additiional trace masks
630#if defined(__WXCOCOA__)
631#include "wx/cocoa/log.h"
632#endif
633
634#endif // _WX_LOG_H_
635