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 wxChar
*szFormat
, va_list argptr
)
89 if ( wxLog::IsEnabled() ) {
90 wxLog::OnLog(level
, wxString::FormatV(szFormat
, argptr
), time(NULL
));
94 void wxLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, ...)
97 va_start(argptr
, szFormat
);
98 wxVLogGeneric(level
, szFormat
, argptr
);
102 #define IMPLEMENT_LOG_FUNCTION(level) \
103 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
105 if ( wxLog::IsEnabled() ) { \
106 wxLog::OnLog(wxLOG_##level, \
107 wxString::FormatV(szFormat, argptr), time(NULL));\
111 void wxLog##level(const wxChar *szFormat, ...) \
114 va_start(argptr, szFormat); \
115 wxVLog##level(szFormat, 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 wxChar
*szFormat
, va_list argptr
)
139 wxSafeShowMessage(_T("Fatal Error"), wxString::FormatV(szFormat
, argptr
));
148 void wxLogFatalError(const wxChar
*szFormat
, ...)
151 va_start(argptr
, szFormat
);
152 wxVLogFatalError(szFormat
, 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 wxChar
*szFormat
, va_list argptr
)
162 if ( wxLog::IsEnabled() ) {
163 if ( wxLog::GetActiveTarget() != NULL
&& wxLog::GetVerbose() ) {
164 wxLog::OnLog(wxLOG_Info
,
165 wxString::FormatV(szFormat
, argptr
), time(NULL
));
170 void wxLogVerbose(const wxChar
*szFormat
, ...)
173 va_start(argptr
, szFormat
);
174 wxVLogVerbose(szFormat
, argptr
);
180 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
181 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
183 if ( wxLog::IsEnabled() ) { \
184 wxLog::OnLog(wxLOG_##level, \
185 wxString::FormatV(szFormat, argptr), time(NULL));\
189 void wxLog##level(const wxChar *szFormat, ...) \
192 va_start(argptr, szFormat); \
193 wxVLog##level(szFormat, argptr); \
197 void wxVLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, va_list argptr
)
199 if ( wxLog::IsEnabled() && wxLog::IsAllowedTraceMask(mask
) ) {
201 msg
<< _T("(") << mask
<< _T(") ") << wxString::FormatV(szFormat
, argptr
);
203 wxLog::OnLog(wxLOG_Trace
, msg
, time(NULL
));
207 void wxLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, ...)
210 va_start(argptr
, szFormat
);
211 wxVLogTrace(mask
, szFormat
, argptr
);
215 void wxVLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, 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(szFormat
, argptr
), time(NULL
));
225 void wxLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, ...)
228 va_start(argptr
, szFormat
);
229 wxVLogTrace(mask
, szFormat
, argptr
);
234 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
237 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
238 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
240 // wxLogSysError: one uses the last error code, for other you must give it
243 // return the system error message description
244 static inline wxString
wxLogSysErrorHelper(long err
)
246 return wxString::Format(_(" (error %ld: %s)"), err
, wxSysErrorMsg(err
));
249 void WXDLLEXPORT
wxVLogSysError(const wxChar
*szFormat
, va_list argptr
)
251 wxVLogSysError(wxSysErrorCode(), szFormat
, argptr
);
254 void WXDLLEXPORT
wxLogSysError(const wxChar
*szFormat
, ...)
257 va_start(argptr
, szFormat
);
258 wxVLogSysError(szFormat
, argptr
);
262 void WXDLLEXPORT
wxVLogSysError(long err
, const wxChar
*fmt
, va_list argptr
)
264 if ( wxLog::IsEnabled() ) {
265 wxLog::OnLog(wxLOG_Error
,
266 wxString::FormatV(fmt
, argptr
) + wxLogSysErrorHelper(err
),
271 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const wxChar
*szFormat
, ...)
274 va_start(argptr
, szFormat
);
275 wxVLogSysError(lErrCode
, szFormat
, argptr
);
279 // ----------------------------------------------------------------------------
280 // wxLog class implementation
281 // ----------------------------------------------------------------------------
284 unsigned wxLog::DoLogNumberOfRepeats()
286 long retval
= ms_prevCounter
;
287 wxLog
*pLogger
= GetActiveTarget();
288 if ( pLogger
&& ms_prevCounter
> 0 )
292 msg
.Printf(wxPLURAL("The previous message repeated once.",
293 "The previous message repeated %lu times.",
297 msg
.Printf(wxT("The previous message was repeated."));
300 ms_prevString
.clear();
301 pLogger
->DoLog(ms_prevLevel
, msg
.c_str(), ms_prevTimeStamp
);
308 if ( ms_prevCounter
> 0 )
310 // looks like the repeat count has not been logged yet,
311 // so let's do it now
312 wxLog::DoLogNumberOfRepeats();
317 void wxLog::OnLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
319 if ( IsEnabled() && ms_logLevel
>= level
)
321 wxLog
*pLogger
= GetActiveTarget();
324 if ( GetRepetitionCounting() && ms_prevString
== szString
)
330 if ( GetRepetitionCounting() )
332 pLogger
->DoLogNumberOfRepeats();
334 ms_prevString
= szString
;
335 ms_prevLevel
= level
;
336 ms_prevTimeStamp
= t
;
337 pLogger
->DoLog(level
, szString
, t
);
343 // deprecated function
344 #if WXWIN_COMPATIBILITY_2_6
346 wxChar
*wxLog::SetLogBuffer(wxChar
* WXUNUSED(buf
), size_t WXUNUSED(size
))
351 #endif // WXWIN_COMPATIBILITY_2_6
353 wxLog
*wxLog::GetActiveTarget()
355 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
356 // prevent infinite recursion if someone calls wxLogXXX() from
357 // wxApp::CreateLogTarget()
358 static bool s_bInGetActiveTarget
= false;
359 if ( !s_bInGetActiveTarget
) {
360 s_bInGetActiveTarget
= true;
362 // ask the application to create a log target for us
363 if ( wxTheApp
!= NULL
)
364 ms_pLogger
= wxTheApp
->GetTraits()->CreateLogTarget();
366 ms_pLogger
= new wxLogStderr
;
368 s_bInGetActiveTarget
= false;
370 // do nothing if it fails - what can we do?
377 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
379 if ( ms_pLogger
!= NULL
) {
380 // flush the old messages before changing because otherwise they might
381 // get lost later if this target is not restored
385 wxLog
*pOldLogger
= ms_pLogger
;
386 ms_pLogger
= pLogger
;
391 void wxLog::DontCreateOnDemand()
393 ms_bAutoCreate
= false;
395 // this is usually called at the end of the program and we assume that it
396 // is *always* called at the end - so we free memory here to avoid false
397 // memory leak reports from wxWin memory tracking code
401 void wxLog::RemoveTraceMask(const wxString
& str
)
403 int index
= ms_aTraceMasks
.Index(str
);
404 if ( index
!= wxNOT_FOUND
)
405 ms_aTraceMasks
.RemoveAt((size_t)index
);
408 void wxLog::ClearTraceMasks()
410 ms_aTraceMasks
.Clear();
413 void wxLog::TimeStamp(wxString
*str
)
420 (void)time(&timeNow
);
423 wxStrftime(buf
, WXSIZEOF(buf
),
424 ms_timestamp
, wxLocaltime_r(&timeNow
, &tm
));
427 *str
<< buf
<< wxT(": ");
429 #endif // wxUSE_DATETIME
432 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
435 case wxLOG_FatalError
:
436 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
437 DoLogString(_("Program aborted."), t
);
447 DoLogString(wxString(_("Error: ")) + szString
, t
);
451 DoLogString(wxString(_("Warning: ")) + szString
, t
);
458 default: // log unknown log levels too
459 DoLogString(szString
, t
);
466 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
476 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
478 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
483 // nothing to do here
486 /*static*/ bool wxLog::IsAllowedTraceMask(const wxChar
*mask
)
488 for ( wxArrayString::iterator it
= ms_aTraceMasks
.begin(),
489 en
= ms_aTraceMasks
.end();
496 // ----------------------------------------------------------------------------
497 // wxLogBuffer implementation
498 // ----------------------------------------------------------------------------
500 void wxLogBuffer::Flush()
502 if ( !m_str
.empty() )
504 wxMessageOutputBest out
;
505 out
.Printf(_T("%s"), m_str
.c_str());
510 void wxLogBuffer::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
517 // don't put debug messages in the buffer, we don't want to show
518 // them to the user in a msg box, log them immediately
524 wxMessageOutputDebug dbgout
;
525 dbgout
.Printf(_T("%s\n"), str
.c_str());
527 #endif // __WXDEBUG__
531 wxLog::DoLog(level
, szString
, t
);
535 void wxLogBuffer::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
537 m_str
<< szString
<< _T("\n");
540 // ----------------------------------------------------------------------------
541 // wxLogStderr class implementation
542 // ----------------------------------------------------------------------------
544 wxLogStderr::wxLogStderr(FILE *fp
)
552 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
559 wxFputc(_T('\n'), m_fp
);
562 // under GUI systems such as Windows or Mac, programs usually don't have
563 // stderr at all, so show the messages also somewhere else, typically in
564 // the debugger window so that they go at least somewhere instead of being
566 if ( m_fp
== stderr
)
568 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
569 if ( traits
&& !traits
->HasStderr() )
571 wxMessageOutputDebug dbgout
;
572 dbgout
.Printf(_T("%s\n"), str
.c_str());
577 // ----------------------------------------------------------------------------
578 // wxLogStream implementation
579 // ----------------------------------------------------------------------------
581 #if wxUSE_STD_IOSTREAM
582 #include "wx/ioswrap.h"
583 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
586 m_ostr
= &wxSTD cerr
;
591 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
595 (*m_ostr
) << wxConvertWX2MB(str
) << wxConvertWX2MB(szString
) << wxSTD endl
;
597 #endif // wxUSE_STD_IOSTREAM
599 // ----------------------------------------------------------------------------
601 // ----------------------------------------------------------------------------
603 wxLogChain::wxLogChain(wxLog
*logger
)
605 m_bPassMessages
= true;
608 m_logOld
= wxLog::SetActiveTarget(this);
611 wxLogChain::~wxLogChain()
615 if ( m_logNew
!= this )
619 void wxLogChain::SetLog(wxLog
*logger
)
621 if ( m_logNew
!= this )
627 void wxLogChain::Flush()
632 // be careful to avoid infinite recursion
633 if ( m_logNew
&& m_logNew
!= this )
637 void wxLogChain::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
639 // let the previous logger show it
640 if ( m_logOld
&& IsPassingMessages() )
642 // bogus cast just to access protected DoLog
643 ((wxLogChain
*)m_logOld
)->DoLog(level
, szString
, t
);
646 if ( m_logNew
&& m_logNew
!= this )
649 ((wxLogChain
*)m_logNew
)->DoLog(level
, szString
, t
);
653 // ----------------------------------------------------------------------------
655 // ----------------------------------------------------------------------------
658 // "'this' : used in base member initializer list" - so what?
659 #pragma warning(disable:4355)
662 wxLogPassThrough::wxLogPassThrough()
668 #pragma warning(default:4355)
671 // ============================================================================
672 // Global functions/variables
673 // ============================================================================
675 // ----------------------------------------------------------------------------
677 // ----------------------------------------------------------------------------
679 bool wxLog::ms_bRepetCounting
= false;
680 wxString
wxLog::ms_prevString
;
681 unsigned int wxLog::ms_prevCounter
= 0;
682 time_t wxLog::ms_prevTimeStamp
= 0;
683 wxLogLevel
wxLog::ms_prevLevel
;
685 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
686 bool wxLog::ms_doLog
= true;
687 bool wxLog::ms_bAutoCreate
= true;
688 bool wxLog::ms_bVerbose
= false;
690 wxLogLevel
wxLog::ms_logLevel
= wxLOG_Max
; // log everything by default
692 size_t wxLog::ms_suspendCount
= 0;
694 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
696 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
697 wxArrayString
wxLog::ms_aTraceMasks
;
699 // ----------------------------------------------------------------------------
700 // stdout error logging helper
701 // ----------------------------------------------------------------------------
703 // helper function: wraps the message and justifies it under given position
704 // (looks more pretty on the terminal). Also adds newline at the end.
706 // TODO this is now disabled until I find a portable way of determining the
707 // terminal window size (ok, I found it but does anybody really cares?)
708 #ifdef LOG_PRETTY_WRAP
709 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
711 size_t nMax
= 80; // FIXME
712 size_t nStart
= strlen(pszPrefix
);
716 while ( *psz
!= '\0' ) {
717 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
721 if ( *psz
!= '\0' ) {
723 for ( n
= 0; n
< nStart
; n
++ )
726 // as we wrapped, squeeze all white space
727 while ( isspace(*psz
) )
734 #endif //LOG_PRETTY_WRAP
736 // ----------------------------------------------------------------------------
737 // error code/error message retrieval functions
738 // ----------------------------------------------------------------------------
740 // get error code from syste
741 unsigned long wxSysErrorCode()
743 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
744 return ::GetLastError();
750 // get error message from system
751 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
754 nErrCode
= wxSysErrorCode();
756 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
757 static wxChar s_szBuf
[1024];
759 // get error message from system
763 FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
766 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
772 // if this happens, something is seriously wrong, so don't use _() here
774 wxSprintf(s_szBuf
, _T("unknown error %lx"), nErrCode
);
779 // copy it to our buffer and free memory
780 // Crashes on SmartPhone (FIXME)
781 #if !defined(__SMARTPHONE__) /* of WinCE */
784 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
785 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
789 // returned string is capitalized and ended with '\r\n' - bad
790 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
791 size_t len
= wxStrlen(s_szBuf
);
794 if ( s_szBuf
[len
- 2] == wxT('\r') )
795 s_szBuf
[len
- 2] = wxT('\0');
799 #endif // !__SMARTPHONE__
801 s_szBuf
[0] = wxT('\0');
807 static wchar_t s_wzBuf
[1024];
808 wxConvCurrent
->MB2WC(s_wzBuf
, strerror((int)nErrCode
),
809 WXSIZEOF(s_wzBuf
) - 1);
812 return strerror((int)nErrCode
);
814 #endif // __WXMSW__/!__WXMSW__