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"
40 #include "wx/datetime.h"
42 #include "wx/msgout.h"
43 #include "wx/textfile.h"
44 #include "wx/thread.h"
45 #include "wx/wxchar.h"
47 // other standard headers
57 #include "wx/msw/wince/time.h"
60 #if defined(__WINDOWS__)
61 #include "wx/msw/private.h" // includes windows.h
64 // ----------------------------------------------------------------------------
65 // non member functions
66 // ----------------------------------------------------------------------------
68 // define this to enable wrapping of log messages
69 //#define LOG_PRETTY_WRAP
71 #ifdef LOG_PRETTY_WRAP
72 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
75 // ============================================================================
77 // ============================================================================
79 // ----------------------------------------------------------------------------
80 // implementation of Log functions
82 // NB: unfortunately we need all these distinct functions, we can't make them
83 // macros and not all compilers inline vararg functions.
84 // ----------------------------------------------------------------------------
86 // generic log function
87 void wxVLogGeneric(wxLogLevel level
, const wxString
& format
, va_list argptr
)
89 if ( wxLog::IsEnabled() ) {
90 wxLog::OnLog(level
, wxString::FormatV(format
, argptr
), time(NULL
));
94 void wxDoLogGeneric(wxLogLevel level
, const wxString
& format
, ...)
97 va_start(argptr
, format
);
98 wxVLogGeneric(level
, format
, argptr
);
102 #define IMPLEMENT_LOG_FUNCTION(level) \
103 void wxVLog##level(const wxString& format, va_list argptr) \
105 if ( wxLog::IsEnabled() ) { \
106 wxLog::OnLog(wxLOG_##level, \
107 wxString::FormatV(format, argptr), time(NULL)); \
111 void wxDoLog##level(const wxString& format, ...) \
114 va_start(argptr, format); \
115 wxVLog##level(format, argptr); \
119 IMPLEMENT_LOG_FUNCTION(Error
)
120 IMPLEMENT_LOG_FUNCTION(Warning
)
121 IMPLEMENT_LOG_FUNCTION(Message
)
122 IMPLEMENT_LOG_FUNCTION(Info
)
123 IMPLEMENT_LOG_FUNCTION(Status
)
125 void wxSafeShowMessage(const wxString
& title
, const wxString
& text
)
128 ::MessageBox(NULL
, text
, title
, MB_OK
| MB_ICONSTOP
);
130 wxFprintf(stderr
, _T("%s: %s\n"), title
.c_str(), text
.c_str());
135 // fatal errors can't be suppressed nor handled by the custom log target and
136 // always terminate the program
137 void wxVLogFatalError(const wxString
& format
, va_list argptr
)
139 wxSafeShowMessage(_T("Fatal Error"), wxString::FormatV(format
, argptr
));
148 void wxDoLogFatalError(const wxString
& format
, ...)
151 va_start(argptr
, format
);
152 wxVLogFatalError(format
, argptr
);
154 // some compilers warn about unreachable code and it shouldn't matter
155 // for the others anyhow...
159 // same as info, but only if 'verbose' mode is on
160 void wxVLogVerbose(const wxString
& format
, va_list argptr
)
162 if ( wxLog::IsEnabled() ) {
163 if ( wxLog::GetActiveTarget() != NULL
&& wxLog::GetVerbose() ) {
164 wxLog::OnLog(wxLOG_Info
,
165 wxString::FormatV(format
, argptr
), time(NULL
));
170 void wxDoLogVerbose(const wxString
& format
, ...)
173 va_start(argptr
, format
);
174 wxVLogVerbose(format
, argptr
);
180 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
181 void wxVLog##level(const wxString& format, va_list argptr) \
183 if ( wxLog::IsEnabled() ) { \
184 wxLog::OnLog(wxLOG_##level, \
185 wxString::FormatV(format, argptr), time(NULL)); \
189 void wxDoLog##level(const wxString& format, ...) \
192 va_start(argptr, format); \
193 wxVLog##level(format, argptr); \
197 void wxVLogTrace(const wxString
& mask
, const wxString
& format
, va_list argptr
)
199 if ( wxLog::IsEnabled() && wxLog::IsAllowedTraceMask(mask
) ) {
201 msg
<< _T("(") << mask
<< _T(") ") << wxString::FormatV(format
, argptr
);
203 wxLog::OnLog(wxLOG_Trace
, msg
, time(NULL
));
207 void wxDoLogTrace(const wxString
& mask
, const wxString
& format
, ...)
210 va_start(argptr
, format
);
211 wxVLogTrace(mask
, format
, argptr
);
215 void wxVLogTrace(wxTraceMask mask
, const wxString
& format
, va_list argptr
)
217 // we check that all of mask bits are set in the current mask, so
218 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
219 // if both bits are set.
220 if ( wxLog::IsEnabled() && ((wxLog::GetTraceMask() & mask
) == mask
) ) {
221 wxLog::OnLog(wxLOG_Trace
, wxString::FormatV(format
, argptr
), time(NULL
));
225 void wxDoLogTrace(wxTraceMask mask
, const wxString
& format
, ...)
228 va_start(argptr
, format
);
229 wxVLogTrace(mask
, format
, argptr
);
234 // workaround for http://bugzilla.openwatcom.org/show_bug.cgi?id=351
235 void wxDoLogTrace(int mask
, const wxString
& format
, ...)
238 va_start(argptr
, format
);
239 wxVLogTrace(mask
, format
, argptr
);
243 void wxDoLogTrace(const char *mask
, const wxString
& format
, ...)
246 va_start(argptr
, format
);
247 wxVLogTrace(mask
, format
, argptr
);
251 void wxDoLogTrace(const wchar_t *mask
, const wxString
& format
, ...)
254 va_start(argptr
, format
);
255 wxVLogTrace(mask
, format
, argptr
);
259 void wxVLogTrace(int mask
, const wxString
& format
, va_list argptr
)
260 { wxVLogTrace((wxTraceMask
)mask
, format
, argptr
); }
261 void wxVLogTrace(const char *mask
, const wxString
& format
, va_list argptr
)
262 { wxVLogTrace(wxString(mask
), format
, argptr
); }
263 void wxVLogTrace(const wchar_t *mask
, const wxString
& format
, va_list argptr
)
264 { wxVLogTrace(wxString(mask
), format
, argptr
); }
265 #endif // __WATCOMC__
268 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
271 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
272 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
274 // wxLogSysError: one uses the last error code, for other you must give it
277 // return the system error message description
278 static inline wxString
wxLogSysErrorHelper(long err
)
280 return wxString::Format(_(" (error %ld: %s)"), err
, wxSysErrorMsg(err
));
283 void WXDLLEXPORT
wxVLogSysError(const wxString
& format
, va_list argptr
)
285 wxVLogSysError(wxSysErrorCode(), format
, argptr
);
288 void WXDLLEXPORT
wxDoLogSysError(const wxString
& format
, ...)
291 va_start(argptr
, format
);
292 wxVLogSysError(format
, argptr
);
296 void WXDLLEXPORT
wxVLogSysError(long err
, const wxString
& format
, va_list argptr
)
298 if ( wxLog::IsEnabled() ) {
299 wxLog::OnLog(wxLOG_Error
,
300 wxString::FormatV(format
, argptr
) + wxLogSysErrorHelper(err
),
305 void WXDLLEXPORT
wxDoLogSysError(long lErrCode
, const wxString
& format
, ...)
308 va_start(argptr
, format
);
309 wxVLogSysError(lErrCode
, format
, argptr
);
314 // workaround for http://bugzilla.openwatcom.org/show_bug.cgi?id=351
315 void WXDLLEXPORT
wxDoLogSysError(unsigned long lErrCode
, const wxString
& format
, ...)
318 va_start(argptr
, format
);
319 wxVLogSysError(lErrCode
, format
, argptr
);
323 void WXDLLEXPORT
wxVLogSysError(unsigned long err
, const wxString
& format
, va_list argptr
)
324 { wxVLogSysError((long)err
, format
, argptr
); }
325 #endif // __WATCOMC__
327 // ----------------------------------------------------------------------------
328 // wxLog class implementation
329 // ----------------------------------------------------------------------------
332 unsigned wxLog::DoLogNumberOfRepeats()
334 long retval
= ms_prevCounter
;
335 wxLog
*pLogger
= GetActiveTarget();
336 if ( pLogger
&& ms_prevCounter
> 0 )
340 msg
.Printf(wxPLURAL("The previous message repeated once.",
341 "The previous message repeated %lu times.",
345 msg
.Printf(wxT("The previous message was repeated."));
348 ms_prevString
.clear();
349 pLogger
->DoLog(ms_prevLevel
, msg
.c_str(), ms_prevTimeStamp
);
356 if ( ms_prevCounter
> 0 )
358 // looks like the repeat count has not been logged yet,
359 // so let's do it now
360 wxLog::DoLogNumberOfRepeats();
365 void wxLog::OnLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
367 if ( IsEnabled() && ms_logLevel
>= level
)
369 wxLog
*pLogger
= GetActiveTarget();
372 if ( GetRepetitionCounting() && ms_prevString
== szString
)
378 if ( GetRepetitionCounting() )
380 DoLogNumberOfRepeats();
382 ms_prevString
= szString
;
383 ms_prevLevel
= level
;
384 ms_prevTimeStamp
= t
;
385 pLogger
->DoLog(level
, szString
, t
);
391 // deprecated function
392 #if WXWIN_COMPATIBILITY_2_6
394 wxChar
*wxLog::SetLogBuffer(wxChar
* WXUNUSED(buf
), size_t WXUNUSED(size
))
399 #endif // WXWIN_COMPATIBILITY_2_6
401 wxLog
*wxLog::GetActiveTarget()
403 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
404 // prevent infinite recursion if someone calls wxLogXXX() from
405 // wxApp::CreateLogTarget()
406 static bool s_bInGetActiveTarget
= false;
407 if ( !s_bInGetActiveTarget
) {
408 s_bInGetActiveTarget
= true;
410 // ask the application to create a log target for us
411 if ( wxTheApp
!= NULL
)
412 ms_pLogger
= wxTheApp
->GetTraits()->CreateLogTarget();
414 ms_pLogger
= new wxLogStderr
;
416 s_bInGetActiveTarget
= false;
418 // do nothing if it fails - what can we do?
425 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
427 if ( ms_pLogger
!= NULL
) {
428 // flush the old messages before changing because otherwise they might
429 // get lost later if this target is not restored
433 wxLog
*pOldLogger
= ms_pLogger
;
434 ms_pLogger
= pLogger
;
439 void wxLog::DontCreateOnDemand()
441 ms_bAutoCreate
= false;
443 // this is usually called at the end of the program and we assume that it
444 // is *always* called at the end - so we free memory here to avoid false
445 // memory leak reports from wxWin memory tracking code
449 void wxLog::RemoveTraceMask(const wxString
& str
)
451 int index
= ms_aTraceMasks
.Index(str
);
452 if ( index
!= wxNOT_FOUND
)
453 ms_aTraceMasks
.RemoveAt((size_t)index
);
456 void wxLog::ClearTraceMasks()
458 ms_aTraceMasks
.Clear();
461 void wxLog::TimeStamp(wxString
*str
)
468 (void)time(&timeNow
);
471 wxStrftime(buf
, WXSIZEOF(buf
),
472 ms_timestamp
, wxLocaltime_r(&timeNow
, &tm
));
475 *str
<< buf
<< wxT(": ");
477 #endif // wxUSE_DATETIME
480 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
483 case wxLOG_FatalError
:
484 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
485 DoLogString(_("Program aborted."), t
);
495 DoLogString(wxString(_("Error: ")) + szString
, t
);
499 DoLogString(wxString(_("Warning: ")) + szString
, t
);
506 default: // log unknown log levels too
507 DoLogString(szString
, t
);
514 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
524 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
526 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
531 // nothing to do here
534 /*static*/ bool wxLog::IsAllowedTraceMask(const wxChar
*mask
)
536 for ( wxArrayString::iterator it
= ms_aTraceMasks
.begin(),
537 en
= ms_aTraceMasks
.end();
544 // ----------------------------------------------------------------------------
545 // wxLogBuffer implementation
546 // ----------------------------------------------------------------------------
548 void wxLogBuffer::Flush()
550 if ( !m_str
.empty() )
552 wxMessageOutputBest out
;
553 out
.Printf(_T("%s"), m_str
.c_str());
558 void wxLogBuffer::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
565 // don't put debug messages in the buffer, we don't want to show
566 // them to the user in a msg box, log them immediately
572 wxMessageOutputDebug dbgout
;
573 dbgout
.Printf(_T("%s\n"), str
.c_str());
575 #endif // __WXDEBUG__
579 wxLog::DoLog(level
, szString
, t
);
583 void wxLogBuffer::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
585 m_str
<< szString
<< _T("\n");
588 // ----------------------------------------------------------------------------
589 // wxLogStderr class implementation
590 // ----------------------------------------------------------------------------
592 wxLogStderr::wxLogStderr(FILE *fp
)
600 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
607 wxFputc(_T('\n'), m_fp
);
610 // under GUI systems such as Windows or Mac, programs usually don't have
611 // stderr at all, so show the messages also somewhere else, typically in
612 // the debugger window so that they go at least somewhere instead of being
614 if ( m_fp
== stderr
)
616 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
617 if ( traits
&& !traits
->HasStderr() )
619 wxMessageOutputDebug dbgout
;
620 dbgout
.Printf(_T("%s\n"), str
.c_str());
625 // ----------------------------------------------------------------------------
626 // wxLogStream implementation
627 // ----------------------------------------------------------------------------
629 #if wxUSE_STD_IOSTREAM
630 #include "wx/ioswrap.h"
631 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
634 m_ostr
= &wxSTD cerr
;
639 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
643 (*m_ostr
) << wxConvertWX2MB(str
) << wxConvertWX2MB(szString
) << wxSTD endl
;
645 #endif // wxUSE_STD_IOSTREAM
647 // ----------------------------------------------------------------------------
649 // ----------------------------------------------------------------------------
651 wxLogChain::wxLogChain(wxLog
*logger
)
653 m_bPassMessages
= true;
656 m_logOld
= wxLog::SetActiveTarget(this);
659 wxLogChain::~wxLogChain()
663 if ( m_logNew
!= this )
667 void wxLogChain::SetLog(wxLog
*logger
)
669 if ( m_logNew
!= this )
675 void wxLogChain::Flush()
680 // be careful to avoid infinite recursion
681 if ( m_logNew
&& m_logNew
!= this )
685 void wxLogChain::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
687 // let the previous logger show it
688 if ( m_logOld
&& IsPassingMessages() )
690 // bogus cast just to access protected DoLog
691 ((wxLogChain
*)m_logOld
)->DoLog(level
, szString
, t
);
694 if ( m_logNew
&& m_logNew
!= this )
697 ((wxLogChain
*)m_logNew
)->DoLog(level
, szString
, t
);
701 // ----------------------------------------------------------------------------
703 // ----------------------------------------------------------------------------
706 // "'this' : used in base member initializer list" - so what?
707 #pragma warning(disable:4355)
710 wxLogPassThrough::wxLogPassThrough()
716 #pragma warning(default:4355)
719 // ============================================================================
720 // Global functions/variables
721 // ============================================================================
723 // ----------------------------------------------------------------------------
725 // ----------------------------------------------------------------------------
727 bool wxLog::ms_bRepetCounting
= false;
728 wxString
wxLog::ms_prevString
;
729 unsigned int wxLog::ms_prevCounter
= 0;
730 time_t wxLog::ms_prevTimeStamp
= 0;
731 wxLogLevel
wxLog::ms_prevLevel
;
733 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
734 bool wxLog::ms_doLog
= true;
735 bool wxLog::ms_bAutoCreate
= true;
736 bool wxLog::ms_bVerbose
= false;
738 wxLogLevel
wxLog::ms_logLevel
= wxLOG_Max
; // log everything by default
740 size_t wxLog::ms_suspendCount
= 0;
742 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
744 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
745 wxArrayString
wxLog::ms_aTraceMasks
;
747 // ----------------------------------------------------------------------------
748 // stdout error logging helper
749 // ----------------------------------------------------------------------------
751 // helper function: wraps the message and justifies it under given position
752 // (looks more pretty on the terminal). Also adds newline at the end.
754 // TODO this is now disabled until I find a portable way of determining the
755 // terminal window size (ok, I found it but does anybody really cares?)
756 #ifdef LOG_PRETTY_WRAP
757 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
759 size_t nMax
= 80; // FIXME
760 size_t nStart
= strlen(pszPrefix
);
764 while ( *psz
!= '\0' ) {
765 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
769 if ( *psz
!= '\0' ) {
771 for ( n
= 0; n
< nStart
; n
++ )
774 // as we wrapped, squeeze all white space
775 while ( isspace(*psz
) )
782 #endif //LOG_PRETTY_WRAP
784 // ----------------------------------------------------------------------------
785 // error code/error message retrieval functions
786 // ----------------------------------------------------------------------------
788 // get error code from syste
789 unsigned long wxSysErrorCode()
791 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
792 return ::GetLastError();
798 // get error message from system
799 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
802 nErrCode
= wxSysErrorCode();
804 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
805 static wxChar s_szBuf
[1024];
807 // get error message from system
811 FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
814 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
820 // if this happens, something is seriously wrong, so don't use _() here
822 wxSprintf(s_szBuf
, _T("unknown error %lx"), nErrCode
);
827 // copy it to our buffer and free memory
828 // Crashes on SmartPhone (FIXME)
829 #if !defined(__SMARTPHONE__) /* of WinCE */
832 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
833 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
837 // returned string is capitalized and ended with '\r\n' - bad
838 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
839 size_t len
= wxStrlen(s_szBuf
);
842 if ( s_szBuf
[len
- 2] == wxT('\r') )
843 s_szBuf
[len
- 2] = wxT('\0');
847 #endif // !__SMARTPHONE__
849 s_szBuf
[0] = wxT('\0');
855 static wchar_t s_wzBuf
[1024];
856 wxConvCurrent
->MB2WC(s_wzBuf
, strerror((int)nErrCode
),
857 WXSIZEOF(s_wzBuf
) - 1);
860 return strerror((int)nErrCode
);
862 #endif // __WXMSW__/!__WXMSW__