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 // ----------------------------------------------------------------------------
79 // implementation of Log functions
81 // NB: unfortunately we need all these distinct functions, we can't make them
82 // macros and not all compilers inline vararg functions.
83 // ----------------------------------------------------------------------------
85 // generic log function
86 void wxVLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, va_list argptr
)
88 if ( wxLog::IsEnabled() ) {
89 wxLog::OnLog(level
, wxString::FormatV(szFormat
, argptr
), time(NULL
));
93 void wxLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, ...)
96 va_start(argptr
, szFormat
);
97 wxVLogGeneric(level
, szFormat
, argptr
);
101 #define IMPLEMENT_LOG_FUNCTION(level) \
102 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
104 if ( wxLog::IsEnabled() ) { \
105 wxLog::OnLog(wxLOG_##level, \
106 wxString::FormatV(szFormat, argptr), time(NULL));\
110 void wxLog##level(const wxChar *szFormat, ...) \
113 va_start(argptr, szFormat); \
114 wxVLog##level(szFormat, argptr); \
118 IMPLEMENT_LOG_FUNCTION(Error
)
119 IMPLEMENT_LOG_FUNCTION(Warning
)
120 IMPLEMENT_LOG_FUNCTION(Message
)
121 IMPLEMENT_LOG_FUNCTION(Info
)
122 IMPLEMENT_LOG_FUNCTION(Status
)
124 void wxSafeShowMessage(const wxString
& title
, const wxString
& text
)
127 ::MessageBox(NULL
, text
, title
, MB_OK
| MB_ICONSTOP
);
129 wxFprintf(stderr
, _T("%s: %s\n"), title
.c_str(), text
.c_str());
134 // fatal errors can't be suppressed nor handled by the custom log target and
135 // always terminate the program
136 void wxVLogFatalError(const wxChar
*szFormat
, va_list argptr
)
138 wxSafeShowMessage(_T("Fatal Error"), wxString::FormatV(szFormat
, argptr
));
147 void wxLogFatalError(const wxChar
*szFormat
, ...)
150 va_start(argptr
, szFormat
);
151 wxVLogFatalError(szFormat
, argptr
);
153 // some compilers warn about unreachable code and it shouldn't matter
154 // for the others anyhow...
158 // same as info, but only if 'verbose' mode is on
159 void wxVLogVerbose(const wxChar
*szFormat
, va_list argptr
)
161 if ( wxLog::IsEnabled() ) {
162 if ( wxLog::GetActiveTarget() != NULL
&& wxLog::GetVerbose() ) {
163 wxLog::OnLog(wxLOG_Info
,
164 wxString::FormatV(szFormat
, argptr
), time(NULL
));
169 void wxLogVerbose(const wxChar
*szFormat
, ...)
172 va_start(argptr
, szFormat
);
173 wxVLogVerbose(szFormat
, argptr
);
179 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
180 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
182 if ( wxLog::IsEnabled() ) { \
183 wxLog::OnLog(wxLOG_##level, \
184 wxString::FormatV(szFormat, argptr), time(NULL));\
188 void wxLog##level(const wxChar *szFormat, ...) \
191 va_start(argptr, szFormat); \
192 wxVLog##level(szFormat, argptr); \
196 void wxVLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, va_list argptr
)
198 if ( wxLog::IsEnabled() && wxLog::IsAllowedTraceMask(mask
) ) {
200 msg
<< _T("(") << mask
<< _T(") ") << wxString::FormatV(szFormat
, argptr
);
202 wxLog::OnLog(wxLOG_Trace
, msg
, time(NULL
));
206 void wxLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, ...)
209 va_start(argptr
, szFormat
);
210 wxVLogTrace(mask
, szFormat
, argptr
);
214 void wxVLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, va_list argptr
)
216 // we check that all of mask bits are set in the current mask, so
217 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
218 // if both bits are set.
219 if ( wxLog::IsEnabled() && ((wxLog::GetTraceMask() & mask
) == mask
) ) {
220 wxLog::OnLog(wxLOG_Trace
, wxString::FormatV(szFormat
, argptr
), time(NULL
));
224 void wxLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, ...)
227 va_start(argptr
, szFormat
);
228 wxVLogTrace(mask
, szFormat
, argptr
);
233 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
236 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
237 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
239 // wxLogSysError: one uses the last error code, for other you must give it
242 // return the system error message description
243 static inline wxString
wxLogSysErrorHelper(long err
)
245 return wxString::Format(_(" (error %ld: %s)"), err
, wxSysErrorMsg(err
));
248 void WXDLLEXPORT
wxVLogSysError(const wxChar
*szFormat
, va_list argptr
)
250 wxVLogSysError(wxSysErrorCode(), szFormat
, argptr
);
253 void WXDLLEXPORT
wxLogSysError(const wxChar
*szFormat
, ...)
256 va_start(argptr
, szFormat
);
257 wxVLogSysError(szFormat
, argptr
);
261 void WXDLLEXPORT
wxVLogSysError(long err
, const wxChar
*fmt
, va_list argptr
)
263 if ( wxLog::IsEnabled() ) {
264 wxLog::OnLog(wxLOG_Error
,
265 wxString::FormatV(fmt
, argptr
) + wxLogSysErrorHelper(err
),
270 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const wxChar
*szFormat
, ...)
273 va_start(argptr
, szFormat
);
274 wxVLogSysError(lErrCode
, szFormat
, argptr
);
278 // ----------------------------------------------------------------------------
279 // wxLog class implementation
280 // ----------------------------------------------------------------------------
283 unsigned wxLog::DoLogNumberOfRepeats()
285 long retval
= ms_prevCounter
;
286 wxLog
*pLogger
= GetActiveTarget();
287 if ( pLogger
&& ms_prevCounter
> 0 )
291 msg
.Printf(wxPLURAL("The previous message repeated once.",
292 "The previous message repeated %lu times.",
296 msg
.Printf(wxT("The previous message was repeated."));
299 ms_prevString
.clear();
300 pLogger
->DoLog(ms_prevLevel
, msg
.c_str(), ms_prevTimeStamp
);
307 if ( ms_prevCounter
> 0 )
309 // looks like the repeat count has not been logged yet,
310 // so let's do it now
311 wxLog::DoLogNumberOfRepeats();
316 void wxLog::OnLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
318 if ( IsEnabled() && ms_logLevel
>= level
)
320 wxLog
*pLogger
= GetActiveTarget();
323 if ( GetRepetitionCounting() && ms_prevString
== szString
)
329 if ( GetRepetitionCounting() )
331 pLogger
->DoLogNumberOfRepeats();
333 ms_prevString
= szString
;
334 ms_prevLevel
= level
;
335 ms_prevTimeStamp
= t
;
336 pLogger
->DoLog(level
, szString
, t
);
342 // deprecated function
343 #if WXWIN_COMPATIBILITY_2_6
345 wxChar
*wxLog::SetLogBuffer(wxChar
* WXUNUSED(buf
), size_t WXUNUSED(size
))
350 #endif // WXWIN_COMPATIBILITY_2_6
352 wxLog
*wxLog::GetActiveTarget()
354 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
355 // prevent infinite recursion if someone calls wxLogXXX() from
356 // wxApp::CreateLogTarget()
357 static bool s_bInGetActiveTarget
= false;
358 if ( !s_bInGetActiveTarget
) {
359 s_bInGetActiveTarget
= true;
361 // ask the application to create a log target for us
362 if ( wxTheApp
!= NULL
)
363 ms_pLogger
= wxTheApp
->GetTraits()->CreateLogTarget();
365 ms_pLogger
= new wxLogStderr
;
367 s_bInGetActiveTarget
= false;
369 // do nothing if it fails - what can we do?
376 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
378 if ( ms_pLogger
!= NULL
) {
379 // flush the old messages before changing because otherwise they might
380 // get lost later if this target is not restored
384 wxLog
*pOldLogger
= ms_pLogger
;
385 ms_pLogger
= pLogger
;
390 void wxLog::DontCreateOnDemand()
392 ms_bAutoCreate
= false;
394 // this is usually called at the end of the program and we assume that it
395 // is *always* called at the end - so we free memory here to avoid false
396 // memory leak reports from wxWin memory tracking code
400 void wxLog::RemoveTraceMask(const wxString
& str
)
402 int index
= ms_aTraceMasks
.Index(str
);
403 if ( index
!= wxNOT_FOUND
)
404 ms_aTraceMasks
.RemoveAt((size_t)index
);
407 void wxLog::ClearTraceMasks()
409 ms_aTraceMasks
.Clear();
412 void wxLog::TimeStamp(wxString
*str
)
418 (void)time(&timeNow
);
419 wxStrftime(buf
, WXSIZEOF(buf
), ms_timestamp
, localtime(&timeNow
));
422 *str
<< buf
<< wxT(": ");
426 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
429 case wxLOG_FatalError
:
430 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
431 DoLogString(_("Program aborted."), t
);
441 DoLogString(wxString(_("Error: ")) + szString
, t
);
445 DoLogString(wxString(_("Warning: ")) + szString
, t
);
452 default: // log unknown log levels too
453 DoLogString(szString
, t
);
460 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
470 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
472 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
477 // nothing to do here
480 /*static*/ bool wxLog::IsAllowedTraceMask(const wxChar
*mask
)
482 for ( wxArrayString::iterator it
= ms_aTraceMasks
.begin(),
483 en
= ms_aTraceMasks
.end();
490 // ----------------------------------------------------------------------------
491 // wxLogBuffer implementation
492 // ----------------------------------------------------------------------------
494 void wxLogBuffer::Flush()
496 if ( !m_str
.empty() )
498 wxMessageOutputBest out
;
499 out
.Printf(_T("%s"), m_str
.c_str());
504 void wxLogBuffer::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
511 // don't put debug messages in the buffer, we don't want to show
512 // them to the user in a msg box, log them immediately
518 wxMessageOutputDebug dbgout
;
519 dbgout
.Printf(_T("%s\n"), str
.c_str());
521 #endif // __WXDEBUG__
525 wxLog::DoLog(level
, szString
, t
);
529 void wxLogBuffer::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
531 m_str
<< szString
<< _T("\n");
534 // ----------------------------------------------------------------------------
535 // wxLogStderr class implementation
536 // ----------------------------------------------------------------------------
538 wxLogStderr::wxLogStderr(FILE *fp
)
546 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
552 fputs(str
.mb_str(), m_fp
);
553 fputc(_T('\n'), m_fp
);
556 // under GUI systems such as Windows or Mac, programs usually don't have
557 // stderr at all, so show the messages also somewhere else, typically in
558 // the debugger window so that they go at least somewhere instead of being
560 if ( m_fp
== stderr
)
562 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
563 if ( traits
&& !traits
->HasStderr() )
565 wxMessageOutputDebug dbgout
;
566 dbgout
.Printf(_T("%s\n"), str
.c_str());
571 // ----------------------------------------------------------------------------
572 // wxLogStream implementation
573 // ----------------------------------------------------------------------------
575 #if wxUSE_STD_IOSTREAM
576 #include "wx/ioswrap.h"
577 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
580 m_ostr
= &wxSTD cerr
;
585 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
589 (*m_ostr
) << wxConvertWX2MB(str
) << wxConvertWX2MB(szString
) << wxSTD endl
;
591 #endif // wxUSE_STD_IOSTREAM
593 // ----------------------------------------------------------------------------
595 // ----------------------------------------------------------------------------
597 wxLogChain::wxLogChain(wxLog
*logger
)
599 m_bPassMessages
= true;
602 m_logOld
= wxLog::SetActiveTarget(this);
605 wxLogChain::~wxLogChain()
609 if ( m_logNew
!= this )
613 void wxLogChain::SetLog(wxLog
*logger
)
615 if ( m_logNew
!= this )
621 void wxLogChain::Flush()
626 // be careful to avoid infinite recursion
627 if ( m_logNew
&& m_logNew
!= this )
631 void wxLogChain::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
633 // let the previous logger show it
634 if ( m_logOld
&& IsPassingMessages() )
636 // bogus cast just to access protected DoLog
637 ((wxLogChain
*)m_logOld
)->DoLog(level
, szString
, t
);
640 if ( m_logNew
&& m_logNew
!= this )
643 ((wxLogChain
*)m_logNew
)->DoLog(level
, szString
, t
);
647 // ----------------------------------------------------------------------------
649 // ----------------------------------------------------------------------------
652 // "'this' : used in base member initializer list" - so what?
653 #pragma warning(disable:4355)
656 wxLogPassThrough::wxLogPassThrough()
662 #pragma warning(default:4355)
665 // ============================================================================
666 // Global functions/variables
667 // ============================================================================
669 // ----------------------------------------------------------------------------
671 // ----------------------------------------------------------------------------
673 bool wxLog::ms_bRepetCounting
= false;
674 wxString
wxLog::ms_prevString
;
675 unsigned int wxLog::ms_prevCounter
= 0;
676 time_t wxLog::ms_prevTimeStamp
= 0;
677 wxLogLevel
wxLog::ms_prevLevel
;
679 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
680 bool wxLog::ms_doLog
= true;
681 bool wxLog::ms_bAutoCreate
= true;
682 bool wxLog::ms_bVerbose
= false;
684 wxLogLevel
wxLog::ms_logLevel
= wxLOG_Max
; // log everything by default
686 size_t wxLog::ms_suspendCount
= 0;
688 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
690 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
691 wxArrayString
wxLog::ms_aTraceMasks
;
693 // ----------------------------------------------------------------------------
694 // stdout error logging helper
695 // ----------------------------------------------------------------------------
697 // helper function: wraps the message and justifies it under given position
698 // (looks more pretty on the terminal). Also adds newline at the end.
700 // TODO this is now disabled until I find a portable way of determining the
701 // terminal window size (ok, I found it but does anybody really cares?)
702 #ifdef LOG_PRETTY_WRAP
703 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
705 size_t nMax
= 80; // FIXME
706 size_t nStart
= strlen(pszPrefix
);
710 while ( *psz
!= '\0' ) {
711 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
715 if ( *psz
!= '\0' ) {
717 for ( n
= 0; n
< nStart
; n
++ )
720 // as we wrapped, squeeze all white space
721 while ( isspace(*psz
) )
728 #endif //LOG_PRETTY_WRAP
730 // ----------------------------------------------------------------------------
731 // error code/error message retrieval functions
732 // ----------------------------------------------------------------------------
734 // get error code from syste
735 unsigned long wxSysErrorCode()
737 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
738 return ::GetLastError();
744 // get error message from system
745 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
748 nErrCode
= wxSysErrorCode();
750 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
751 static wxChar s_szBuf
[1024];
753 // get error message from system
757 FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
760 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
766 // if this happens, something is seriously wrong, so don't use _() here
768 wxSprintf(s_szBuf
, _T("unknown error %lx"), nErrCode
);
773 // copy it to our buffer and free memory
774 // Crashes on SmartPhone (FIXME)
775 #if !defined(__SMARTPHONE__) /* of WinCE */
778 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
779 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
783 // returned string is capitalized and ended with '\r\n' - bad
784 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
785 size_t len
= wxStrlen(s_szBuf
);
788 if ( s_szBuf
[len
- 2] == wxT('\r') )
789 s_szBuf
[len
- 2] = wxT('\0');
793 #endif // !__SMARTPHONE__
795 s_szBuf
[0] = wxT('\0');
801 static wchar_t s_wzBuf
[1024];
802 wxConvCurrent
->MB2WC(s_wzBuf
, strerror((int)nErrCode
),
803 WXSIZEOF(s_wzBuf
) - 1);
806 return strerror((int)nErrCode
);
808 #endif // __WXMSW__/!__WXMSW__