1 /////////////////////////////////////////////////////////////////////////////
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"
32 #include "wx/arrstr.h"
34 #include "wx/string.h"
37 #include "wx/apptrait.h"
40 #include "wx/msgout.h"
41 #include "wx/textfile.h"
42 #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 // return true if we have a non NULL non disabled log target
100 static inline bool IsLoggingEnabled()
102 return wxLog::IsEnabled() && (wxLog::GetActiveTarget() != NULL
);
105 // ----------------------------------------------------------------------------
106 // implementation of Log functions
108 // NB: unfortunately we need all these distinct functions, we can't make them
109 // macros and not all compilers inline vararg functions.
110 // ----------------------------------------------------------------------------
112 // wrapper for wxVsnprintf(s_szBuf) which always NULL-terminates it
113 static inline void PrintfInLogBug(const wxChar
*szFormat
, va_list argptr
)
115 if ( wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
) < 0 )
117 // must NUL-terminate it manually
118 s_szBuf
[s_szBufSize
- 1] = _T('\0');
120 //else: NUL-terminated by vsnprintf()
123 // generic log function
124 void wxVLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, va_list argptr
)
126 if ( IsLoggingEnabled() ) {
127 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
129 PrintfInLogBug(szFormat
, argptr
);
131 wxLog::OnLog(level
, s_szBuf
, time(NULL
));
135 void wxLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, ...)
138 va_start(argptr
, szFormat
);
139 wxVLogGeneric(level
, szFormat
, argptr
);
143 #define IMPLEMENT_LOG_FUNCTION(level) \
144 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
146 if ( IsLoggingEnabled() ) { \
147 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
149 PrintfInLogBug(szFormat, argptr); \
151 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
155 void wxLog##level(const wxChar *szFormat, ...) \
158 va_start(argptr, szFormat); \
159 wxVLog##level(szFormat, argptr); \
163 IMPLEMENT_LOG_FUNCTION(Error
)
164 IMPLEMENT_LOG_FUNCTION(Warning
)
165 IMPLEMENT_LOG_FUNCTION(Message
)
166 IMPLEMENT_LOG_FUNCTION(Info
)
167 IMPLEMENT_LOG_FUNCTION(Status
)
169 void wxSafeShowMessage(const wxString
& title
, const wxString
& text
)
172 ::MessageBox(NULL
, text
, title
, MB_OK
| MB_ICONSTOP
);
174 wxFprintf(stderr
, _T("%s: %s\n"), title
.c_str(), text
.c_str());
178 // fatal errors can't be suppressed nor handled by the custom log target and
179 // always terminate the program
180 void wxVLogFatalError(const wxChar
*szFormat
, va_list argptr
)
182 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
184 wxSafeShowMessage(_T("Fatal Error"), s_szBuf
);
193 void wxLogFatalError(const wxChar
*szFormat
, ...)
196 va_start(argptr
, szFormat
);
197 wxVLogFatalError(szFormat
, argptr
);
199 // some compilers warn about unreachable code and it shouldn't matter
200 // for the others anyhow...
204 // same as info, but only if 'verbose' mode is on
205 void wxVLogVerbose(const wxChar
*szFormat
, va_list argptr
)
207 if ( IsLoggingEnabled() ) {
208 if ( wxLog::GetActiveTarget() != NULL
&& wxLog::GetVerbose() ) {
209 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
211 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
213 wxLog::OnLog(wxLOG_Info
, s_szBuf
, time(NULL
));
218 void wxLogVerbose(const wxChar
*szFormat
, ...)
221 va_start(argptr
, szFormat
);
222 wxVLogVerbose(szFormat
, argptr
);
228 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
229 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
231 if ( IsLoggingEnabled() ) { \
232 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
234 wxVsnprintf(s_szBuf, s_szBufSize, szFormat, argptr); \
236 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
239 void wxLog##level(const wxChar *szFormat, ...) \
242 va_start(argptr, szFormat); \
243 wxVLog##level(szFormat, argptr); \
247 void wxVLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, va_list argptr
)
249 if ( IsLoggingEnabled() && wxLog::IsAllowedTraceMask(mask
) ) {
250 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
253 size_t len
= s_szBufSize
;
254 wxStrncpy(s_szBuf
, _T("("), len
);
255 len
-= 1; // strlen("(")
257 wxStrncat(p
, mask
, len
);
258 size_t lenMask
= wxStrlen(mask
);
262 wxStrncat(p
, _T(") "), len
);
266 wxVsnprintf(p
, len
, szFormat
, argptr
);
268 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
272 void wxLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, ...)
275 va_start(argptr
, szFormat
);
276 wxVLogTrace(mask
, szFormat
, argptr
);
280 void wxVLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, va_list argptr
)
282 // we check that all of mask bits are set in the current mask, so
283 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
284 // if both bits are set.
285 if ( IsLoggingEnabled() && ((wxLog::GetTraceMask() & mask
) == mask
) ) {
286 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
288 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
290 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
294 void wxLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, ...)
297 va_start(argptr
, szFormat
);
298 wxVLogTrace(mask
, szFormat
, argptr
);
303 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
306 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
307 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
309 // wxLogSysError: one uses the last error code, for other you must give it
312 // common part of both wxLogSysError
313 void wxLogSysErrorHelper(long lErrCode
)
315 wxChar szErrMsg
[LOG_BUFFER_SIZE
/ 2];
316 wxSnprintf(szErrMsg
, WXSIZEOF(szErrMsg
),
317 _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
318 wxStrncat(s_szBuf
, szErrMsg
, s_szBufSize
- wxStrlen(s_szBuf
));
320 wxLog::OnLog(wxLOG_Error
, s_szBuf
, time(NULL
));
323 void WXDLLEXPORT
wxVLogSysError(const wxChar
*szFormat
, va_list argptr
)
325 if ( IsLoggingEnabled() ) {
326 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
328 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
330 wxLogSysErrorHelper(wxSysErrorCode());
334 void WXDLLEXPORT
wxLogSysError(const wxChar
*szFormat
, ...)
337 va_start(argptr
, szFormat
);
338 wxVLogSysError(szFormat
, argptr
);
342 void WXDLLEXPORT
wxVLogSysError(long lErrCode
, const wxChar
*szFormat
, va_list argptr
)
344 if ( IsLoggingEnabled() ) {
345 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
347 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
349 wxLogSysErrorHelper(lErrCode
);
353 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const wxChar
*szFormat
, ...)
356 va_start(argptr
, szFormat
);
357 wxVLogSysError(lErrCode
, szFormat
, argptr
);
361 // ----------------------------------------------------------------------------
362 // wxLog class implementation
363 // ----------------------------------------------------------------------------
365 wxChar
*wxLog::SetLogBuffer( wxChar
*buf
, size_t size
)
367 wxChar
*oldbuf
= s_szBuf
;
371 s_szBuf
= s_szBufStatic
;
372 s_szBufSize
= WXSIZEOF( s_szBufStatic
);
380 return (oldbuf
== s_szBufStatic
) ? 0 : oldbuf
;
383 wxLog
*wxLog::GetActiveTarget()
385 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
386 // prevent infinite recursion if someone calls wxLogXXX() from
387 // wxApp::CreateLogTarget()
388 static bool s_bInGetActiveTarget
= false;
389 if ( !s_bInGetActiveTarget
) {
390 s_bInGetActiveTarget
= true;
392 // ask the application to create a log target for us
393 if ( wxTheApp
!= NULL
)
394 ms_pLogger
= wxTheApp
->GetTraits()->CreateLogTarget();
396 ms_pLogger
= new wxLogStderr
;
398 s_bInGetActiveTarget
= false;
400 // do nothing if it fails - what can we do?
407 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
409 if ( ms_pLogger
!= NULL
) {
410 // flush the old messages before changing because otherwise they might
411 // get lost later if this target is not restored
415 wxLog
*pOldLogger
= ms_pLogger
;
416 ms_pLogger
= pLogger
;
421 void wxLog::DontCreateOnDemand()
423 ms_bAutoCreate
= false;
425 // this is usually called at the end of the program and we assume that it
426 // is *always* called at the end - so we free memory here to avoid false
427 // memory leak reports from wxWin memory tracking code
431 void wxLog::RemoveTraceMask(const wxString
& str
)
433 int index
= ms_aTraceMasks
.Index(str
);
434 if ( index
!= wxNOT_FOUND
)
435 ms_aTraceMasks
.RemoveAt((size_t)index
);
438 void wxLog::ClearTraceMasks()
440 ms_aTraceMasks
.Clear();
443 void wxLog::TimeStamp(wxString
*str
)
449 (void)time(&timeNow
);
450 wxStrftime(buf
, WXSIZEOF(buf
), ms_timestamp
, localtime(&timeNow
));
453 *str
<< buf
<< wxT(": ");
457 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
460 case wxLOG_FatalError
:
461 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
462 DoLogString(_("Program aborted."), t
);
472 DoLogString(wxString(_("Error: ")) + szString
, t
);
476 DoLogString(wxString(_("Warning: ")) + szString
, t
);
483 default: // log unknown log levels too
484 DoLogString(szString
, t
);
491 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
501 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
503 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
508 // nothing to do here
511 /*static*/ bool wxLog::IsAllowedTraceMask(const wxChar
*mask
)
513 for ( wxArrayString::iterator it
= ms_aTraceMasks
.begin(),
514 en
= ms_aTraceMasks
.end();
521 // ----------------------------------------------------------------------------
522 // wxLogBuffer implementation
523 // ----------------------------------------------------------------------------
525 void wxLogBuffer::Flush()
527 if ( !m_str
.empty() )
529 wxMessageOutputBest out
;
530 out
.Printf(_T("%s"), m_str
.c_str());
535 void wxLogBuffer::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
542 // don't put debug messages in the buffer, we don't want to show
543 // them to the user in a msg box, log them immediately
549 wxMessageOutputDebug dbgout
;
550 dbgout
.Printf(_T("%s\n"), str
.c_str());
552 #endif // __WXDEBUG__
556 wxLog::DoLog(level
, szString
, t
);
560 void wxLogBuffer::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
562 m_str
<< szString
<< _T("\n");
565 // ----------------------------------------------------------------------------
566 // wxLogStderr class implementation
567 // ----------------------------------------------------------------------------
569 wxLogStderr::wxLogStderr(FILE *fp
)
577 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
583 fputs(str
.mb_str(), m_fp
);
584 fputc(_T('\n'), m_fp
);
587 // under GUI systems such as Windows or Mac, programs usually don't have
588 // stderr at all, so show the messages also somewhere else, typically in
589 // the debugger window so that they go at least somewhere instead of being
591 if ( m_fp
== stderr
)
593 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
594 if ( traits
&& !traits
->HasStderr() )
596 wxMessageOutputDebug dbgout
;
597 dbgout
.Printf(_T("%s\n"), str
.c_str());
602 // ----------------------------------------------------------------------------
603 // wxLogStream implementation
604 // ----------------------------------------------------------------------------
606 #if wxUSE_STD_IOSTREAM
607 #include "wx/ioswrap.h"
608 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
611 m_ostr
= &wxSTD cerr
;
616 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
620 (*m_ostr
) << wxConvertWX2MB(str
) << wxConvertWX2MB(szString
) << wxSTD endl
;
622 #endif // wxUSE_STD_IOSTREAM
624 // ----------------------------------------------------------------------------
626 // ----------------------------------------------------------------------------
628 wxLogChain::wxLogChain(wxLog
*logger
)
630 m_bPassMessages
= true;
633 m_logOld
= wxLog::SetActiveTarget(this);
636 wxLogChain::~wxLogChain()
640 if ( m_logNew
!= this )
644 void wxLogChain::SetLog(wxLog
*logger
)
646 if ( m_logNew
!= this )
652 void wxLogChain::Flush()
657 // be careful to avoid infinite recursion
658 if ( m_logNew
&& m_logNew
!= this )
662 void wxLogChain::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
664 // let the previous logger show it
665 if ( m_logOld
&& IsPassingMessages() )
667 // bogus cast just to access protected DoLog
668 ((wxLogChain
*)m_logOld
)->DoLog(level
, szString
, t
);
671 if ( m_logNew
&& m_logNew
!= this )
674 ((wxLogChain
*)m_logNew
)->DoLog(level
, szString
, t
);
678 // ----------------------------------------------------------------------------
680 // ----------------------------------------------------------------------------
683 // "'this' : used in base member initializer list" - so what?
684 #pragma warning(disable:4355)
687 wxLogPassThrough::wxLogPassThrough()
693 #pragma warning(default:4355)
696 // ============================================================================
697 // Global functions/variables
698 // ============================================================================
700 // ----------------------------------------------------------------------------
702 // ----------------------------------------------------------------------------
704 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
705 bool wxLog::ms_doLog
= true;
706 bool wxLog::ms_bAutoCreate
= true;
707 bool wxLog::ms_bVerbose
= false;
709 wxLogLevel
wxLog::ms_logLevel
= wxLOG_Max
; // log everything by default
711 size_t wxLog::ms_suspendCount
= 0;
713 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
715 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
716 wxArrayString
wxLog::ms_aTraceMasks
;
718 // ----------------------------------------------------------------------------
719 // stdout error logging helper
720 // ----------------------------------------------------------------------------
722 // helper function: wraps the message and justifies it under given position
723 // (looks more pretty on the terminal). Also adds newline at the end.
725 // TODO this is now disabled until I find a portable way of determining the
726 // terminal window size (ok, I found it but does anybody really cares?)
727 #ifdef LOG_PRETTY_WRAP
728 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
730 size_t nMax
= 80; // FIXME
731 size_t nStart
= strlen(pszPrefix
);
735 while ( *psz
!= '\0' ) {
736 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
740 if ( *psz
!= '\0' ) {
742 for ( n
= 0; n
< nStart
; n
++ )
745 // as we wrapped, squeeze all white space
746 while ( isspace(*psz
) )
753 #endif //LOG_PRETTY_WRAP
755 // ----------------------------------------------------------------------------
756 // error code/error message retrieval functions
757 // ----------------------------------------------------------------------------
759 // get error code from syste
760 unsigned long wxSysErrorCode()
762 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
763 return ::GetLastError();
769 // get error message from system
770 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
773 nErrCode
= wxSysErrorCode();
775 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
776 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
778 // get error message from system
782 FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
785 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
791 // if this happens, something is seriously wrong, so don't use _() here
793 wxSprintf(s_szBuf
, _T("unknown error %lx"), nErrCode
);
798 // copy it to our buffer and free memory
799 // Crashes on SmartPhone (FIXME)
800 #if !defined(__SMARTPHONE__) /* of WinCE */
803 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
804 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
808 // returned string is capitalized and ended with '\r\n' - bad
809 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
810 size_t len
= wxStrlen(s_szBuf
);
813 if ( s_szBuf
[len
- 2] == wxT('\r') )
814 s_szBuf
[len
- 2] = wxT('\0');
820 s_szBuf
[0] = wxT('\0');
824 #else // Unix-WXMICROWIN
826 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
827 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
830 return strerror((int)nErrCode
);
832 #endif // Win/Unix-WXMICROWIN