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 // ----------------------------------------------------------------------------
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 // ----------------------------------------------------------------------------
100 // implementation of Log functions
102 // NB: unfortunately we need all these distinct functions, we can't make them
103 // macros and not all compilers inline vararg functions.
104 // ----------------------------------------------------------------------------
106 // wrapper for wxVsnprintf(s_szBuf) which always NULL-terminates it
107 static inline void PrintfInLogBuf(const wxChar
*szFormat
, va_list argptr
)
109 if ( wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
) < 0 )
111 // must NUL-terminate it manually
112 s_szBuf
[s_szBufSize
- 1] = _T('\0');
114 //else: NUL-terminated by vsnprintf()
117 // generic log function
118 void wxVLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, va_list argptr
)
120 if ( wxLog::IsEnabled() ) {
121 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
123 PrintfInLogBuf(szFormat
, argptr
);
125 wxLog::OnLog(level
, s_szBuf
, time(NULL
));
129 void wxLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, ...)
132 va_start(argptr
, szFormat
);
133 wxVLogGeneric(level
, szFormat
, argptr
);
137 #define IMPLEMENT_LOG_FUNCTION(level) \
138 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
140 if ( wxLog::IsEnabled() ) { \
141 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
143 PrintfInLogBuf(szFormat, argptr); \
145 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
149 void wxLog##level(const wxChar *szFormat, ...) \
152 va_start(argptr, szFormat); \
153 wxVLog##level(szFormat, argptr); \
157 IMPLEMENT_LOG_FUNCTION(Error
)
158 IMPLEMENT_LOG_FUNCTION(Warning
)
159 IMPLEMENT_LOG_FUNCTION(Message
)
160 IMPLEMENT_LOG_FUNCTION(Info
)
161 IMPLEMENT_LOG_FUNCTION(Status
)
163 void wxSafeShowMessage(const wxString
& title
, const wxString
& text
)
166 ::MessageBox(NULL
, text
, title
, MB_OK
| MB_ICONSTOP
);
168 wxFprintf(stderr
, _T("%s: %s\n"), title
.c_str(), text
.c_str());
172 // fatal errors can't be suppressed nor handled by the custom log target and
173 // always terminate the program
174 void wxVLogFatalError(const wxChar
*szFormat
, va_list argptr
)
176 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
178 wxSafeShowMessage(_T("Fatal Error"), s_szBuf
);
187 void wxLogFatalError(const wxChar
*szFormat
, ...)
190 va_start(argptr
, szFormat
);
191 wxVLogFatalError(szFormat
, argptr
);
193 // some compilers warn about unreachable code and it shouldn't matter
194 // for the others anyhow...
198 // same as info, but only if 'verbose' mode is on
199 void wxVLogVerbose(const wxChar
*szFormat
, va_list argptr
)
201 if ( wxLog::IsEnabled() ) {
202 if ( wxLog::GetActiveTarget() != NULL
&& wxLog::GetVerbose() ) {
203 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
205 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
207 wxLog::OnLog(wxLOG_Info
, s_szBuf
, time(NULL
));
212 void wxLogVerbose(const wxChar
*szFormat
, ...)
215 va_start(argptr
, szFormat
);
216 wxVLogVerbose(szFormat
, argptr
);
222 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
223 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
225 if ( wxLog::IsEnabled() ) { \
226 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
228 wxVsnprintf(s_szBuf, s_szBufSize, szFormat, argptr); \
230 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
233 void wxLog##level(const wxChar *szFormat, ...) \
236 va_start(argptr, szFormat); \
237 wxVLog##level(szFormat, argptr); \
241 void wxVLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, va_list argptr
)
243 if ( wxLog::IsEnabled() && wxLog::IsAllowedTraceMask(mask
) ) {
244 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
247 size_t len
= s_szBufSize
;
248 wxStrncpy(s_szBuf
, _T("("), len
);
249 len
-= 1; // strlen("(")
251 wxStrncat(p
, mask
, len
);
252 size_t lenMask
= wxStrlen(mask
);
256 wxStrncat(p
, _T(") "), len
);
260 wxVsnprintf(p
, len
, szFormat
, argptr
);
262 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
266 void wxLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, ...)
269 va_start(argptr
, szFormat
);
270 wxVLogTrace(mask
, szFormat
, argptr
);
274 void wxVLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, va_list argptr
)
276 // we check that all of mask bits are set in the current mask, so
277 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
278 // if both bits are set.
279 if ( wxLog::IsEnabled() && ((wxLog::GetTraceMask() & mask
) == mask
) ) {
280 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
282 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
284 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
288 void wxLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, ...)
291 va_start(argptr
, szFormat
);
292 wxVLogTrace(mask
, szFormat
, argptr
);
297 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
300 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
301 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
303 // wxLogSysError: one uses the last error code, for other you must give it
306 // common part of both wxLogSysError
307 void wxLogSysErrorHelper(long lErrCode
)
309 wxChar szErrMsg
[LOG_BUFFER_SIZE
/ 2];
310 wxSnprintf(szErrMsg
, WXSIZEOF(szErrMsg
),
311 _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
312 wxStrncat(s_szBuf
, szErrMsg
, s_szBufSize
- wxStrlen(s_szBuf
));
314 wxLog::OnLog(wxLOG_Error
, s_szBuf
, time(NULL
));
317 void WXDLLEXPORT
wxVLogSysError(const wxChar
*szFormat
, va_list argptr
)
319 if ( wxLog::IsEnabled() ) {
320 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
322 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
324 wxLogSysErrorHelper(wxSysErrorCode());
328 void WXDLLEXPORT
wxLogSysError(const wxChar
*szFormat
, ...)
331 va_start(argptr
, szFormat
);
332 wxVLogSysError(szFormat
, argptr
);
336 void WXDLLEXPORT
wxVLogSysError(long lErrCode
, const wxChar
*szFormat
, va_list argptr
)
338 if ( wxLog::IsEnabled() ) {
339 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
341 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
343 wxLogSysErrorHelper(lErrCode
);
347 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const wxChar
*szFormat
, ...)
350 va_start(argptr
, szFormat
);
351 wxVLogSysError(lErrCode
, szFormat
, argptr
);
355 // ----------------------------------------------------------------------------
356 // wxLog class implementation
357 // ----------------------------------------------------------------------------
359 wxChar
*wxLog::SetLogBuffer( wxChar
*buf
, size_t size
)
361 wxChar
*oldbuf
= s_szBuf
;
365 s_szBuf
= s_szBufStatic
;
366 s_szBufSize
= WXSIZEOF( s_szBufStatic
);
374 return (oldbuf
== s_szBufStatic
) ? 0 : oldbuf
;
377 wxLog
*wxLog::GetActiveTarget()
379 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
380 // prevent infinite recursion if someone calls wxLogXXX() from
381 // wxApp::CreateLogTarget()
382 static bool s_bInGetActiveTarget
= false;
383 if ( !s_bInGetActiveTarget
) {
384 s_bInGetActiveTarget
= true;
386 // ask the application to create a log target for us
387 if ( wxTheApp
!= NULL
)
388 ms_pLogger
= wxTheApp
->GetTraits()->CreateLogTarget();
390 ms_pLogger
= new wxLogStderr
;
392 s_bInGetActiveTarget
= false;
394 // do nothing if it fails - what can we do?
401 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
403 if ( ms_pLogger
!= NULL
) {
404 // flush the old messages before changing because otherwise they might
405 // get lost later if this target is not restored
409 wxLog
*pOldLogger
= ms_pLogger
;
410 ms_pLogger
= pLogger
;
415 void wxLog::DontCreateOnDemand()
417 ms_bAutoCreate
= false;
419 // this is usually called at the end of the program and we assume that it
420 // is *always* called at the end - so we free memory here to avoid false
421 // memory leak reports from wxWin memory tracking code
425 void wxLog::RemoveTraceMask(const wxString
& str
)
427 int index
= ms_aTraceMasks
.Index(str
);
428 if ( index
!= wxNOT_FOUND
)
429 ms_aTraceMasks
.RemoveAt((size_t)index
);
432 void wxLog::ClearTraceMasks()
434 ms_aTraceMasks
.Clear();
437 void wxLog::TimeStamp(wxString
*str
)
443 (void)time(&timeNow
);
444 wxStrftime(buf
, WXSIZEOF(buf
), ms_timestamp
, localtime(&timeNow
));
447 *str
<< buf
<< wxT(": ");
451 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
454 case wxLOG_FatalError
:
455 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
456 DoLogString(_("Program aborted."), t
);
466 DoLogString(wxString(_("Error: ")) + szString
, t
);
470 DoLogString(wxString(_("Warning: ")) + szString
, t
);
477 default: // log unknown log levels too
478 DoLogString(szString
, t
);
485 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
495 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
497 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
502 // nothing to do here
505 /*static*/ bool wxLog::IsAllowedTraceMask(const wxChar
*mask
)
507 for ( wxArrayString::iterator it
= ms_aTraceMasks
.begin(),
508 en
= ms_aTraceMasks
.end();
515 // ----------------------------------------------------------------------------
516 // wxLogBuffer implementation
517 // ----------------------------------------------------------------------------
519 void wxLogBuffer::Flush()
521 if ( !m_str
.empty() )
523 wxMessageOutputBest out
;
524 out
.Printf(_T("%s"), m_str
.c_str());
529 void wxLogBuffer::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
536 // don't put debug messages in the buffer, we don't want to show
537 // them to the user in a msg box, log them immediately
543 wxMessageOutputDebug dbgout
;
544 dbgout
.Printf(_T("%s\n"), str
.c_str());
546 #endif // __WXDEBUG__
550 wxLog::DoLog(level
, szString
, t
);
554 void wxLogBuffer::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
556 m_str
<< szString
<< _T("\n");
559 // ----------------------------------------------------------------------------
560 // wxLogStderr class implementation
561 // ----------------------------------------------------------------------------
563 wxLogStderr::wxLogStderr(FILE *fp
)
571 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
577 fputs(str
.mb_str(), m_fp
);
578 fputc(_T('\n'), m_fp
);
581 // under GUI systems such as Windows or Mac, programs usually don't have
582 // stderr at all, so show the messages also somewhere else, typically in
583 // the debugger window so that they go at least somewhere instead of being
585 if ( m_fp
== stderr
)
587 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
588 if ( traits
&& !traits
->HasStderr() )
590 wxMessageOutputDebug dbgout
;
591 dbgout
.Printf(_T("%s\n"), str
.c_str());
596 // ----------------------------------------------------------------------------
597 // wxLogStream implementation
598 // ----------------------------------------------------------------------------
600 #if wxUSE_STD_IOSTREAM
601 #include "wx/ioswrap.h"
602 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
605 m_ostr
= &wxSTD cerr
;
610 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
614 (*m_ostr
) << wxConvertWX2MB(str
) << wxConvertWX2MB(szString
) << wxSTD endl
;
616 #endif // wxUSE_STD_IOSTREAM
618 // ----------------------------------------------------------------------------
620 // ----------------------------------------------------------------------------
622 wxLogChain::wxLogChain(wxLog
*logger
)
624 m_bPassMessages
= true;
627 m_logOld
= wxLog::SetActiveTarget(this);
630 wxLogChain::~wxLogChain()
634 if ( m_logNew
!= this )
638 void wxLogChain::SetLog(wxLog
*logger
)
640 if ( m_logNew
!= this )
646 void wxLogChain::Flush()
651 // be careful to avoid infinite recursion
652 if ( m_logNew
&& m_logNew
!= this )
656 void wxLogChain::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
658 // let the previous logger show it
659 if ( m_logOld
&& IsPassingMessages() )
661 // bogus cast just to access protected DoLog
662 ((wxLogChain
*)m_logOld
)->DoLog(level
, szString
, t
);
665 if ( m_logNew
&& m_logNew
!= this )
668 ((wxLogChain
*)m_logNew
)->DoLog(level
, szString
, t
);
672 // ----------------------------------------------------------------------------
674 // ----------------------------------------------------------------------------
677 // "'this' : used in base member initializer list" - so what?
678 #pragma warning(disable:4355)
681 wxLogPassThrough::wxLogPassThrough()
687 #pragma warning(default:4355)
690 // ============================================================================
691 // Global functions/variables
692 // ============================================================================
694 // ----------------------------------------------------------------------------
696 // ----------------------------------------------------------------------------
698 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
699 bool wxLog::ms_doLog
= true;
700 bool wxLog::ms_bAutoCreate
= true;
701 bool wxLog::ms_bVerbose
= false;
703 wxLogLevel
wxLog::ms_logLevel
= wxLOG_Max
; // log everything by default
705 size_t wxLog::ms_suspendCount
= 0;
707 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
709 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
710 wxArrayString
wxLog::ms_aTraceMasks
;
712 // ----------------------------------------------------------------------------
713 // stdout error logging helper
714 // ----------------------------------------------------------------------------
716 // helper function: wraps the message and justifies it under given position
717 // (looks more pretty on the terminal). Also adds newline at the end.
719 // TODO this is now disabled until I find a portable way of determining the
720 // terminal window size (ok, I found it but does anybody really cares?)
721 #ifdef LOG_PRETTY_WRAP
722 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
724 size_t nMax
= 80; // FIXME
725 size_t nStart
= strlen(pszPrefix
);
729 while ( *psz
!= '\0' ) {
730 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
734 if ( *psz
!= '\0' ) {
736 for ( n
= 0; n
< nStart
; n
++ )
739 // as we wrapped, squeeze all white space
740 while ( isspace(*psz
) )
747 #endif //LOG_PRETTY_WRAP
749 // ----------------------------------------------------------------------------
750 // error code/error message retrieval functions
751 // ----------------------------------------------------------------------------
753 // get error code from syste
754 unsigned long wxSysErrorCode()
756 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
757 return ::GetLastError();
763 // get error message from system
764 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
767 nErrCode
= wxSysErrorCode();
769 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
770 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
772 // get error message from system
776 FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
779 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
785 // if this happens, something is seriously wrong, so don't use _() here
787 wxSprintf(s_szBuf
, _T("unknown error %lx"), nErrCode
);
792 // copy it to our buffer and free memory
793 // Crashes on SmartPhone (FIXME)
794 #if !defined(__SMARTPHONE__) /* of WinCE */
797 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
798 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
802 // returned string is capitalized and ended with '\r\n' - bad
803 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
804 size_t len
= wxStrlen(s_szBuf
);
807 if ( s_szBuf
[len
- 2] == wxT('\r') )
808 s_szBuf
[len
- 2] = wxT('\0');
814 s_szBuf
[0] = wxT('\0');
818 #else // Unix-WXMICROWIN
820 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
821 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
824 return strerror((int)nErrCode
);
826 #endif // Win/Unix-WXMICROWIN