1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/log.cpp
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 licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
33 #include "wx/arrstr.h"
35 #include "wx/string.h"
39 #include "wx/apptrait.h"
41 #include "wx/msgout.h"
42 #include "wx/textfile.h"
43 #include "wx/thread.h"
44 #include "wx/wxchar.h"
46 // other standard headers
56 #include "wx/msw/wince/time.h"
59 #if defined(__WINDOWS__)
60 #include "wx/msw/private.h" // includes windows.h
63 // ----------------------------------------------------------------------------
64 // non member functions
65 // ----------------------------------------------------------------------------
67 // define this to enable wrapping of log messages
68 //#define LOG_PRETTY_WRAP
70 #ifdef LOG_PRETTY_WRAP
71 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
74 // ============================================================================
76 // ============================================================================
78 // ----------------------------------------------------------------------------
80 // ----------------------------------------------------------------------------
82 // log functions can't allocate memory (LogError("out of memory...") should
83 // work!), so we use a static buffer for all log messages
84 #define LOG_BUFFER_SIZE (4096)
86 // static buffer for error messages
87 static wxChar s_szBufStatic
[LOG_BUFFER_SIZE
];
89 static wxChar
*s_szBuf
= s_szBufStatic
;
90 static size_t s_szBufSize
= WXSIZEOF( s_szBufStatic
);
94 // the critical section protecting the static buffer
95 static wxCriticalSection gs_csLogBuf
;
97 #endif // wxUSE_THREADS
99 // ----------------------------------------------------------------------------
100 // implementation of Log functions
102 // NB: unfortunately we need all these distinct functions, we can't make them
103 // macros and not all compilers inline vararg functions.
104 // ----------------------------------------------------------------------------
106 // wrapper for wxVsnprintf(s_szBuf) which always NULL-terminates it
107 static inline void PrintfInLogBuf(const wxChar
*szFormat
, va_list argptr
)
109 if ( wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
) < 0 )
111 // must NUL-terminate it manually
112 s_szBuf
[s_szBufSize
- 1] = _T('\0');
114 //else: NUL-terminated by vsnprintf()
117 // generic log function
118 void wxVLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, va_list argptr
)
120 if ( wxLog::IsEnabled() ) {
121 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
123 PrintfInLogBuf(szFormat
, argptr
);
125 wxLog::OnLog(level
, s_szBuf
, time(NULL
));
129 void wxLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, ...)
132 va_start(argptr
, szFormat
);
133 wxVLogGeneric(level
, szFormat
, argptr
);
137 #define IMPLEMENT_LOG_FUNCTION(level) \
138 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
140 if ( wxLog::IsEnabled() ) { \
141 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
143 PrintfInLogBuf(szFormat, argptr); \
145 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
149 void wxLog##level(const wxChar *szFormat, ...) \
152 va_start(argptr, szFormat); \
153 wxVLog##level(szFormat, argptr); \
157 IMPLEMENT_LOG_FUNCTION(Error
)
158 IMPLEMENT_LOG_FUNCTION(Warning
)
159 IMPLEMENT_LOG_FUNCTION(Message
)
160 IMPLEMENT_LOG_FUNCTION(Info
)
161 IMPLEMENT_LOG_FUNCTION(Status
)
163 void wxSafeShowMessage(const wxString
& title
, const wxString
& text
)
166 ::MessageBox(NULL
, text
, title
, MB_OK
| MB_ICONSTOP
);
168 wxFprintf(stderr
, _T("%s: %s\n"), title
.c_str(), text
.c_str());
173 // fatal errors can't be suppressed nor handled by the custom log target and
174 // always terminate the program
175 void wxVLogFatalError(const wxChar
*szFormat
, va_list argptr
)
177 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
179 wxSafeShowMessage(_T("Fatal Error"), s_szBuf
);
188 void wxLogFatalError(const wxChar
*szFormat
, ...)
191 va_start(argptr
, szFormat
);
192 wxVLogFatalError(szFormat
, argptr
);
194 // some compilers warn about unreachable code and it shouldn't matter
195 // for the others anyhow...
199 // same as info, but only if 'verbose' mode is on
200 void wxVLogVerbose(const wxChar
*szFormat
, va_list argptr
)
202 if ( wxLog::IsEnabled() ) {
203 if ( wxLog::GetActiveTarget() != NULL
&& wxLog::GetVerbose() ) {
204 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
206 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
208 wxLog::OnLog(wxLOG_Info
, s_szBuf
, time(NULL
));
213 void wxLogVerbose(const wxChar
*szFormat
, ...)
216 va_start(argptr
, szFormat
);
217 wxVLogVerbose(szFormat
, argptr
);
223 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
224 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
226 if ( wxLog::IsEnabled() ) { \
227 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
229 wxVsnprintf(s_szBuf, s_szBufSize, szFormat, argptr); \
231 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
234 void wxLog##level(const wxChar *szFormat, ...) \
237 va_start(argptr, szFormat); \
238 wxVLog##level(szFormat, argptr); \
242 void wxVLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, va_list argptr
)
244 if ( wxLog::IsEnabled() && wxLog::IsAllowedTraceMask(mask
) ) {
245 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
248 size_t len
= s_szBufSize
;
249 wxStrncpy(s_szBuf
, _T("("), len
);
250 len
-= 1; // strlen("(")
252 wxStrncat(p
, mask
, len
);
253 size_t lenMask
= wxStrlen(mask
);
257 wxStrncat(p
, _T(") "), len
);
261 wxVsnprintf(p
, len
, szFormat
, argptr
);
263 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
267 void wxLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, ...)
270 va_start(argptr
, szFormat
);
271 wxVLogTrace(mask
, szFormat
, argptr
);
275 void wxVLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, va_list argptr
)
277 // we check that all of mask bits are set in the current mask, so
278 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
279 // if both bits are set.
280 if ( wxLog::IsEnabled() && ((wxLog::GetTraceMask() & mask
) == mask
) ) {
281 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
283 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
285 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
289 void wxLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, ...)
292 va_start(argptr
, szFormat
);
293 wxVLogTrace(mask
, szFormat
, argptr
);
298 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
301 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
302 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
304 // wxLogSysError: one uses the last error code, for other you must give it
307 // common part of both wxLogSysError
308 void wxLogSysErrorHelper(long lErrCode
)
310 wxChar szErrMsg
[LOG_BUFFER_SIZE
/ 2];
311 wxSnprintf(szErrMsg
, WXSIZEOF(szErrMsg
),
312 _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
313 wxStrncat(s_szBuf
, szErrMsg
, s_szBufSize
- wxStrlen(s_szBuf
));
315 wxLog::OnLog(wxLOG_Error
, s_szBuf
, time(NULL
));
318 void WXDLLEXPORT
wxVLogSysError(const wxChar
*szFormat
, va_list argptr
)
320 if ( wxLog::IsEnabled() ) {
321 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
323 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
325 wxLogSysErrorHelper(wxSysErrorCode());
329 void WXDLLEXPORT
wxLogSysError(const wxChar
*szFormat
, ...)
332 va_start(argptr
, szFormat
);
333 wxVLogSysError(szFormat
, argptr
);
337 void WXDLLEXPORT
wxVLogSysError(long lErrCode
, const wxChar
*szFormat
, va_list argptr
)
339 if ( wxLog::IsEnabled() ) {
340 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
342 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
344 wxLogSysErrorHelper(lErrCode
);
348 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const wxChar
*szFormat
, ...)
351 va_start(argptr
, szFormat
);
352 wxVLogSysError(lErrCode
, szFormat
, argptr
);
356 // ----------------------------------------------------------------------------
357 // wxLog class implementation
358 // ----------------------------------------------------------------------------
361 unsigned wxLog::DoLogNumberOfRepeats()
363 long retval
= ms_prevCounter
;
364 wxLog
*pLogger
= GetActiveTarget();
365 if ( pLogger
&& ms_prevCounter
> 0 )
369 msg
.Printf(wxPLURAL("The previous message repeated once.",
370 "The previous message repeated %lu times.",
374 msg
.Printf(wxT("The previous message was repeated."));
377 ms_prevString
.clear();
378 pLogger
->DoLog(ms_prevLevel
, msg
.c_str(), ms_prevTimeStamp
);
385 if ( ms_prevCounter
> 0 )
387 // looks like the repeat count has not been logged yet,
388 // so let's do it now
389 wxLog::DoLogNumberOfRepeats();
394 void wxLog::OnLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
396 if ( IsEnabled() && ms_logLevel
>= level
)
398 wxLog
*pLogger
= GetActiveTarget();
401 if ( GetRepetitionCounting() && ms_prevString
== szString
)
407 if ( GetRepetitionCounting() )
409 pLogger
->DoLogNumberOfRepeats();
411 ms_prevString
= szString
;
412 ms_prevLevel
= level
;
413 ms_prevTimeStamp
= t
;
414 pLogger
->DoLog(level
, szString
, t
);
420 wxChar
*wxLog::SetLogBuffer( wxChar
*buf
, size_t size
)
422 wxChar
*oldbuf
= s_szBuf
;
426 s_szBuf
= s_szBufStatic
;
427 s_szBufSize
= WXSIZEOF( s_szBufStatic
);
435 return (oldbuf
== s_szBufStatic
) ? 0 : oldbuf
;
438 wxLog
*wxLog::GetActiveTarget()
440 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
441 // prevent infinite recursion if someone calls wxLogXXX() from
442 // wxApp::CreateLogTarget()
443 static bool s_bInGetActiveTarget
= false;
444 if ( !s_bInGetActiveTarget
) {
445 s_bInGetActiveTarget
= true;
447 // ask the application to create a log target for us
448 if ( wxTheApp
!= NULL
)
449 ms_pLogger
= wxTheApp
->GetTraits()->CreateLogTarget();
451 ms_pLogger
= new wxLogStderr
;
453 s_bInGetActiveTarget
= false;
455 // do nothing if it fails - what can we do?
462 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
464 if ( ms_pLogger
!= NULL
) {
465 // flush the old messages before changing because otherwise they might
466 // get lost later if this target is not restored
470 wxLog
*pOldLogger
= ms_pLogger
;
471 ms_pLogger
= pLogger
;
476 void wxLog::DontCreateOnDemand()
478 ms_bAutoCreate
= false;
480 // this is usually called at the end of the program and we assume that it
481 // is *always* called at the end - so we free memory here to avoid false
482 // memory leak reports from wxWin memory tracking code
486 void wxLog::RemoveTraceMask(const wxString
& str
)
488 int index
= ms_aTraceMasks
.Index(str
);
489 if ( index
!= wxNOT_FOUND
)
490 ms_aTraceMasks
.RemoveAt((size_t)index
);
493 void wxLog::ClearTraceMasks()
495 ms_aTraceMasks
.Clear();
498 void wxLog::TimeStamp(wxString
*str
)
504 (void)time(&timeNow
);
505 wxStrftime(buf
, WXSIZEOF(buf
), ms_timestamp
, localtime(&timeNow
));
508 *str
<< buf
<< wxT(": ");
512 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
515 case wxLOG_FatalError
:
516 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
517 DoLogString(_("Program aborted."), t
);
527 DoLogString(wxString(_("Error: ")) + szString
, t
);
531 DoLogString(wxString(_("Warning: ")) + szString
, t
);
538 default: // log unknown log levels too
539 DoLogString(szString
, t
);
546 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
556 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
558 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
563 // nothing to do here
566 /*static*/ bool wxLog::IsAllowedTraceMask(const wxChar
*mask
)
568 for ( wxArrayString::iterator it
= ms_aTraceMasks
.begin(),
569 en
= ms_aTraceMasks
.end();
576 // ----------------------------------------------------------------------------
577 // wxLogBuffer implementation
578 // ----------------------------------------------------------------------------
580 void wxLogBuffer::Flush()
582 if ( !m_str
.empty() )
584 wxMessageOutputBest out
;
585 out
.Printf(_T("%s"), m_str
.c_str());
590 void wxLogBuffer::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
597 // don't put debug messages in the buffer, we don't want to show
598 // them to the user in a msg box, log them immediately
604 wxMessageOutputDebug dbgout
;
605 dbgout
.Printf(_T("%s\n"), str
.c_str());
607 #endif // __WXDEBUG__
611 wxLog::DoLog(level
, szString
, t
);
615 void wxLogBuffer::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
617 m_str
<< szString
<< _T("\n");
620 // ----------------------------------------------------------------------------
621 // wxLogStderr class implementation
622 // ----------------------------------------------------------------------------
624 wxLogStderr::wxLogStderr(FILE *fp
)
632 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
638 fputs(str
.mb_str(), m_fp
);
639 fputc(_T('\n'), m_fp
);
642 // under GUI systems such as Windows or Mac, programs usually don't have
643 // stderr at all, so show the messages also somewhere else, typically in
644 // the debugger window so that they go at least somewhere instead of being
646 if ( m_fp
== stderr
)
648 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
649 if ( traits
&& !traits
->HasStderr() )
651 wxMessageOutputDebug dbgout
;
652 dbgout
.Printf(_T("%s\n"), str
.c_str());
657 // ----------------------------------------------------------------------------
658 // wxLogStream implementation
659 // ----------------------------------------------------------------------------
661 #if wxUSE_STD_IOSTREAM
662 #include "wx/ioswrap.h"
663 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
666 m_ostr
= &wxSTD cerr
;
671 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
675 (*m_ostr
) << wxConvertWX2MB(str
) << wxConvertWX2MB(szString
) << wxSTD endl
;
677 #endif // wxUSE_STD_IOSTREAM
679 // ----------------------------------------------------------------------------
681 // ----------------------------------------------------------------------------
683 wxLogChain::wxLogChain(wxLog
*logger
)
685 m_bPassMessages
= true;
688 m_logOld
= wxLog::SetActiveTarget(this);
691 wxLogChain::~wxLogChain()
695 if ( m_logNew
!= this )
699 void wxLogChain::SetLog(wxLog
*logger
)
701 if ( m_logNew
!= this )
707 void wxLogChain::Flush()
712 // be careful to avoid infinite recursion
713 if ( m_logNew
&& m_logNew
!= this )
717 void wxLogChain::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
719 // let the previous logger show it
720 if ( m_logOld
&& IsPassingMessages() )
722 // bogus cast just to access protected DoLog
723 ((wxLogChain
*)m_logOld
)->DoLog(level
, szString
, t
);
726 if ( m_logNew
&& m_logNew
!= this )
729 ((wxLogChain
*)m_logNew
)->DoLog(level
, szString
, t
);
733 // ----------------------------------------------------------------------------
735 // ----------------------------------------------------------------------------
738 // "'this' : used in base member initializer list" - so what?
739 #pragma warning(disable:4355)
742 wxLogPassThrough::wxLogPassThrough()
748 #pragma warning(default:4355)
751 // ============================================================================
752 // Global functions/variables
753 // ============================================================================
755 // ----------------------------------------------------------------------------
757 // ----------------------------------------------------------------------------
759 bool wxLog::ms_bRepetCounting
= false;
760 wxString
wxLog::ms_prevString
;
761 unsigned int wxLog::ms_prevCounter
= 0;
762 time_t wxLog::ms_prevTimeStamp
= 0;
763 wxLogLevel
wxLog::ms_prevLevel
;
765 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
766 bool wxLog::ms_doLog
= true;
767 bool wxLog::ms_bAutoCreate
= true;
768 bool wxLog::ms_bVerbose
= false;
770 wxLogLevel
wxLog::ms_logLevel
= wxLOG_Max
; // log everything by default
772 size_t wxLog::ms_suspendCount
= 0;
774 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
776 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
777 wxArrayString
wxLog::ms_aTraceMasks
;
779 // ----------------------------------------------------------------------------
780 // stdout error logging helper
781 // ----------------------------------------------------------------------------
783 // helper function: wraps the message and justifies it under given position
784 // (looks more pretty on the terminal). Also adds newline at the end.
786 // TODO this is now disabled until I find a portable way of determining the
787 // terminal window size (ok, I found it but does anybody really cares?)
788 #ifdef LOG_PRETTY_WRAP
789 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
791 size_t nMax
= 80; // FIXME
792 size_t nStart
= strlen(pszPrefix
);
796 while ( *psz
!= '\0' ) {
797 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
801 if ( *psz
!= '\0' ) {
803 for ( n
= 0; n
< nStart
; n
++ )
806 // as we wrapped, squeeze all white space
807 while ( isspace(*psz
) )
814 #endif //LOG_PRETTY_WRAP
816 // ----------------------------------------------------------------------------
817 // error code/error message retrieval functions
818 // ----------------------------------------------------------------------------
820 // get error code from syste
821 unsigned long wxSysErrorCode()
823 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
824 return ::GetLastError();
830 // get error message from system
831 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
834 nErrCode
= wxSysErrorCode();
836 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
837 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
839 // get error message from system
843 FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
846 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
852 // if this happens, something is seriously wrong, so don't use _() here
854 wxSprintf(s_szBuf
, _T("unknown error %lx"), nErrCode
);
859 // copy it to our buffer and free memory
860 // Crashes on SmartPhone (FIXME)
861 #if !defined(__SMARTPHONE__) /* of WinCE */
864 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
865 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
869 // returned string is capitalized and ended with '\r\n' - bad
870 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
871 size_t len
= wxStrlen(s_szBuf
);
874 if ( s_szBuf
[len
- 2] == wxT('\r') )
875 s_szBuf
[len
- 2] = wxT('\0');
881 s_szBuf
[0] = wxT('\0');
885 #else // Unix-WXMICROWIN
887 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
888 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
891 return strerror((int)nErrCode
);
893 #endif // Win/Unix-WXMICROWIN