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
);
421 wxStrftime(buf
, WXSIZEOF(buf
),
422 ms_timestamp
, wxLocaltime_r(&timeNow
, &tm
));
425 *str
<< buf
<< wxT(": ");
429 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
432 case wxLOG_FatalError
:
433 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
434 DoLogString(_("Program aborted."), t
);
444 DoLogString(wxString(_("Error: ")) + szString
, t
);
448 DoLogString(wxString(_("Warning: ")) + szString
, t
);
455 default: // log unknown log levels too
456 DoLogString(szString
, t
);
463 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
473 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
475 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
480 // nothing to do here
483 /*static*/ bool wxLog::IsAllowedTraceMask(const wxChar
*mask
)
485 for ( wxArrayString::iterator it
= ms_aTraceMasks
.begin(),
486 en
= ms_aTraceMasks
.end();
493 // ----------------------------------------------------------------------------
494 // wxLogBuffer implementation
495 // ----------------------------------------------------------------------------
497 void wxLogBuffer::Flush()
499 if ( !m_str
.empty() )
501 wxMessageOutputBest out
;
502 out
.Printf(_T("%s"), m_str
.c_str());
507 void wxLogBuffer::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
514 // don't put debug messages in the buffer, we don't want to show
515 // them to the user in a msg box, log them immediately
521 wxMessageOutputDebug dbgout
;
522 dbgout
.Printf(_T("%s\n"), str
.c_str());
524 #endif // __WXDEBUG__
528 wxLog::DoLog(level
, szString
, t
);
532 void wxLogBuffer::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
534 m_str
<< szString
<< _T("\n");
537 // ----------------------------------------------------------------------------
538 // wxLogStderr class implementation
539 // ----------------------------------------------------------------------------
541 wxLogStderr::wxLogStderr(FILE *fp
)
549 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
555 fputs(str
.mb_str(), m_fp
);
556 fputc(_T('\n'), m_fp
);
559 // under GUI systems such as Windows or Mac, programs usually don't have
560 // stderr at all, so show the messages also somewhere else, typically in
561 // the debugger window so that they go at least somewhere instead of being
563 if ( m_fp
== stderr
)
565 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
566 if ( traits
&& !traits
->HasStderr() )
568 wxMessageOutputDebug dbgout
;
569 dbgout
.Printf(_T("%s\n"), str
.c_str());
574 // ----------------------------------------------------------------------------
575 // wxLogStream implementation
576 // ----------------------------------------------------------------------------
578 #if wxUSE_STD_IOSTREAM
579 #include "wx/ioswrap.h"
580 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
583 m_ostr
= &wxSTD cerr
;
588 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
592 (*m_ostr
) << wxConvertWX2MB(str
) << wxConvertWX2MB(szString
) << wxSTD endl
;
594 #endif // wxUSE_STD_IOSTREAM
596 // ----------------------------------------------------------------------------
598 // ----------------------------------------------------------------------------
600 wxLogChain::wxLogChain(wxLog
*logger
)
602 m_bPassMessages
= true;
605 m_logOld
= wxLog::SetActiveTarget(this);
608 wxLogChain::~wxLogChain()
612 if ( m_logNew
!= this )
616 void wxLogChain::SetLog(wxLog
*logger
)
618 if ( m_logNew
!= this )
624 void wxLogChain::Flush()
629 // be careful to avoid infinite recursion
630 if ( m_logNew
&& m_logNew
!= this )
634 void wxLogChain::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
636 // let the previous logger show it
637 if ( m_logOld
&& IsPassingMessages() )
639 // bogus cast just to access protected DoLog
640 ((wxLogChain
*)m_logOld
)->DoLog(level
, szString
, t
);
643 if ( m_logNew
&& m_logNew
!= this )
646 ((wxLogChain
*)m_logNew
)->DoLog(level
, szString
, t
);
650 // ----------------------------------------------------------------------------
652 // ----------------------------------------------------------------------------
655 // "'this' : used in base member initializer list" - so what?
656 #pragma warning(disable:4355)
659 wxLogPassThrough::wxLogPassThrough()
665 #pragma warning(default:4355)
668 // ============================================================================
669 // Global functions/variables
670 // ============================================================================
672 // ----------------------------------------------------------------------------
674 // ----------------------------------------------------------------------------
676 bool wxLog::ms_bRepetCounting
= false;
677 wxString
wxLog::ms_prevString
;
678 unsigned int wxLog::ms_prevCounter
= 0;
679 time_t wxLog::ms_prevTimeStamp
= 0;
680 wxLogLevel
wxLog::ms_prevLevel
;
682 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
683 bool wxLog::ms_doLog
= true;
684 bool wxLog::ms_bAutoCreate
= true;
685 bool wxLog::ms_bVerbose
= false;
687 wxLogLevel
wxLog::ms_logLevel
= wxLOG_Max
; // log everything by default
689 size_t wxLog::ms_suspendCount
= 0;
691 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
693 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
694 wxArrayString
wxLog::ms_aTraceMasks
;
696 // ----------------------------------------------------------------------------
697 // stdout error logging helper
698 // ----------------------------------------------------------------------------
700 // helper function: wraps the message and justifies it under given position
701 // (looks more pretty on the terminal). Also adds newline at the end.
703 // TODO this is now disabled until I find a portable way of determining the
704 // terminal window size (ok, I found it but does anybody really cares?)
705 #ifdef LOG_PRETTY_WRAP
706 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
708 size_t nMax
= 80; // FIXME
709 size_t nStart
= strlen(pszPrefix
);
713 while ( *psz
!= '\0' ) {
714 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
718 if ( *psz
!= '\0' ) {
720 for ( n
= 0; n
< nStart
; n
++ )
723 // as we wrapped, squeeze all white space
724 while ( isspace(*psz
) )
731 #endif //LOG_PRETTY_WRAP
733 // ----------------------------------------------------------------------------
734 // error code/error message retrieval functions
735 // ----------------------------------------------------------------------------
737 // get error code from syste
738 unsigned long wxSysErrorCode()
740 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
741 return ::GetLastError();
747 // get error message from system
748 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
751 nErrCode
= wxSysErrorCode();
753 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
754 static wxChar s_szBuf
[1024];
756 // get error message from system
760 FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
763 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
769 // if this happens, something is seriously wrong, so don't use _() here
771 wxSprintf(s_szBuf
, _T("unknown error %lx"), nErrCode
);
776 // copy it to our buffer and free memory
777 // Crashes on SmartPhone (FIXME)
778 #if !defined(__SMARTPHONE__) /* of WinCE */
781 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
782 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
786 // returned string is capitalized and ended with '\r\n' - bad
787 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
788 size_t len
= wxStrlen(s_szBuf
);
791 if ( s_szBuf
[len
- 2] == wxT('\r') )
792 s_szBuf
[len
- 2] = wxT('\0');
796 #endif // !__SMARTPHONE__
798 s_szBuf
[0] = wxT('\0');
804 static wchar_t s_wzBuf
[1024];
805 wxConvCurrent
->MB2WC(s_wzBuf
, strerror((int)nErrCode
),
806 WXSIZEOF(s_wzBuf
) - 1);
809 return strerror((int)nErrCode
);
811 #endif // __WXMSW__/!__WXMSW__