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 // ----------------------------------------------------------------------------
21 #pragma implementation "log.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
37 #include "wx/string.h"
40 #include "wx/apptrait.h"
43 #include "wx/msgout.h"
44 #include "wx/textfile.h"
45 #include "wx/thread.h"
47 #include "wx/wxchar.h"
49 // other standard headers
54 // ----------------------------------------------------------------------------
55 // non member functions
56 // ----------------------------------------------------------------------------
58 // define this to enable wrapping of log messages
59 //#define LOG_PRETTY_WRAP
61 #ifdef LOG_PRETTY_WRAP
62 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
65 // ============================================================================
67 // ============================================================================
69 // ----------------------------------------------------------------------------
71 // ----------------------------------------------------------------------------
73 // log functions can't allocate memory (LogError("out of memory...") should
74 // work!), so we use a static buffer for all log messages
75 #define LOG_BUFFER_SIZE (4096)
77 // static buffer for error messages
78 static wxChar s_szBufStatic
[LOG_BUFFER_SIZE
];
80 static wxChar
*s_szBuf
= s_szBufStatic
;
81 static size_t s_szBufSize
= WXSIZEOF( s_szBufStatic
);
85 // the critical section protecting the static buffer
86 static wxCriticalSection gs_csLogBuf
;
88 #endif // wxUSE_THREADS
90 // return true if we have a non NULL non disabled log target
91 static inline bool IsLoggingEnabled()
93 return wxLog::IsEnabled() && (wxLog::GetActiveTarget() != NULL
);
96 // ----------------------------------------------------------------------------
97 // implementation of Log functions
99 // NB: unfortunately we need all these distinct functions, we can't make them
100 // macros and not all compilers inline vararg functions.
101 // ----------------------------------------------------------------------------
103 // wrapper for wxVsnprintf(s_szBuf) which always NULL-terminates it
104 static inline void PrintfInLogBug(const wxChar
*szFormat
, va_list argptr
)
106 if ( wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
) < 0 )
108 // must NUL-terminate it manually
109 s_szBuf
[s_szBufSize
- 1] = _T('\0');
111 //else: NUL-terminated by vsnprintf()
114 // generic log function
115 void wxVLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, va_list argptr
)
117 if ( IsLoggingEnabled() ) {
118 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
120 PrintfInLogBug(szFormat
, argptr
);
122 wxLog::OnLog(level
, s_szBuf
, time(NULL
));
126 void wxLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, ...)
129 va_start(argptr
, szFormat
);
130 wxVLogGeneric(level
, szFormat
, argptr
);
134 #define IMPLEMENT_LOG_FUNCTION(level) \
135 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
137 if ( IsLoggingEnabled() ) { \
138 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
140 PrintfInLogBug(szFormat, argptr); \
142 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
146 void wxLog##level(const wxChar *szFormat, ...) \
149 va_start(argptr, szFormat); \
150 wxVLog##level(szFormat, argptr); \
154 IMPLEMENT_LOG_FUNCTION(Error
)
155 IMPLEMENT_LOG_FUNCTION(Warning
)
156 IMPLEMENT_LOG_FUNCTION(Message
)
157 IMPLEMENT_LOG_FUNCTION(Info
)
158 IMPLEMENT_LOG_FUNCTION(Status
)
160 void wxSafeShowMessage(const wxString
& title
, const wxString
& text
)
163 ::MessageBox(NULL
, text
, title
, MB_OK
| MB_ICONSTOP
);
165 wxFprintf(stderr
, _T("%s: %s\n"), title
.c_str(), text
.c_str());
169 // fatal errors can't be suppressed nor handled by the custom log target and
170 // always terminate the program
171 void wxVLogFatalError(const wxChar
*szFormat
, va_list argptr
)
173 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
175 wxSafeShowMessage(_T("Fatal Error"), s_szBuf
);
180 void wxLogFatalError(const wxChar
*szFormat
, ...)
183 va_start(argptr
, szFormat
);
184 wxVLogFatalError(szFormat
, argptr
);
188 // same as info, but only if 'verbose' mode is on
189 void wxVLogVerbose(const wxChar
*szFormat
, va_list argptr
)
191 if ( IsLoggingEnabled() ) {
192 wxLog
*pLog
= wxLog::GetActiveTarget();
193 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
194 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
196 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
198 wxLog::OnLog(wxLOG_Info
, s_szBuf
, time(NULL
));
203 void wxLogVerbose(const wxChar
*szFormat
, ...)
206 va_start(argptr
, szFormat
);
207 wxVLogVerbose(szFormat
, argptr
);
213 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
214 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
216 if ( IsLoggingEnabled() ) { \
217 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
219 wxVsnprintf(s_szBuf, s_szBufSize, szFormat, argptr); \
221 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
224 void wxLog##level(const wxChar *szFormat, ...) \
227 va_start(argptr, szFormat); \
228 wxVLog##level(szFormat, argptr); \
232 void wxVLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, va_list argptr
)
234 if ( IsLoggingEnabled() && wxLog::IsAllowedTraceMask(mask
) ) {
235 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
238 size_t len
= s_szBufSize
;
239 wxStrncpy(s_szBuf
, _T("("), len
);
240 len
-= 1; // strlen("(")
242 wxStrncat(p
, mask
, len
);
243 size_t lenMask
= wxStrlen(mask
);
247 wxStrncat(p
, _T(") "), len
);
251 wxVsnprintf(p
, len
, szFormat
, argptr
);
253 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
257 void wxLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, ...)
260 va_start(argptr
, szFormat
);
261 wxVLogTrace(mask
, szFormat
, argptr
);
265 void wxVLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, va_list argptr
)
267 // we check that all of mask bits are set in the current mask, so
268 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
269 // if both bits are set.
270 if ( IsLoggingEnabled() && ((wxLog::GetTraceMask() & mask
) == mask
) ) {
271 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
273 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
275 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
279 void wxLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, ...)
282 va_start(argptr
, szFormat
);
283 wxVLogTrace(mask
, szFormat
, argptr
);
288 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
291 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
292 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
294 // wxLogSysError: one uses the last error code, for other you must give it
297 // common part of both wxLogSysError
298 void wxLogSysErrorHelper(long lErrCode
)
300 wxChar szErrMsg
[LOG_BUFFER_SIZE
/ 2];
301 wxSnprintf(szErrMsg
, WXSIZEOF(szErrMsg
),
302 _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
303 wxStrncat(s_szBuf
, szErrMsg
, s_szBufSize
- wxStrlen(s_szBuf
));
305 wxLog::OnLog(wxLOG_Error
, s_szBuf
, time(NULL
));
308 void WXDLLEXPORT
wxVLogSysError(const wxChar
*szFormat
, va_list argptr
)
310 if ( IsLoggingEnabled() ) {
311 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
313 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
315 wxLogSysErrorHelper(wxSysErrorCode());
319 void WXDLLEXPORT
wxLogSysError(const wxChar
*szFormat
, ...)
322 va_start(argptr
, szFormat
);
323 wxVLogSysError(szFormat
, argptr
);
327 void WXDLLEXPORT
wxVLogSysError(long lErrCode
, const wxChar
*szFormat
, va_list argptr
)
329 if ( IsLoggingEnabled() ) {
330 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
332 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
334 wxLogSysErrorHelper(lErrCode
);
338 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const wxChar
*szFormat
, ...)
341 va_start(argptr
, szFormat
);
342 wxVLogSysError(lErrCode
, szFormat
, argptr
);
346 // ----------------------------------------------------------------------------
347 // wxLog class implementation
348 // ----------------------------------------------------------------------------
354 wxChar
*wxLog::SetLogBuffer( wxChar
*buf
, size_t size
)
356 wxChar
*oldbuf
= s_szBuf
;
360 s_szBuf
= s_szBufStatic
;
361 s_szBufSize
= WXSIZEOF( s_szBufStatic
);
369 return (oldbuf
== s_szBufStatic
) ? 0 : oldbuf
;
372 wxLog
*wxLog::GetActiveTarget()
374 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
375 // prevent infinite recursion if someone calls wxLogXXX() from
376 // wxApp::CreateLogTarget()
377 static bool s_bInGetActiveTarget
= FALSE
;
378 if ( !s_bInGetActiveTarget
) {
379 s_bInGetActiveTarget
= TRUE
;
381 // ask the application to create a log target for us
382 if ( wxTheApp
!= NULL
)
383 ms_pLogger
= wxTheApp
->CreateLogTarget();
385 ms_pLogger
= new wxLogStderr
;
387 s_bInGetActiveTarget
= FALSE
;
389 // do nothing if it fails - what can we do?
396 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
398 if ( ms_pLogger
!= NULL
) {
399 // flush the old messages before changing because otherwise they might
400 // get lost later if this target is not restored
404 wxLog
*pOldLogger
= ms_pLogger
;
405 ms_pLogger
= pLogger
;
410 void wxLog::DontCreateOnDemand()
412 ms_bAutoCreate
= FALSE
;
414 // this is usually called at the end of the program and we assume that it
415 // is *always* called at the end - so we free memory here to avoid false
416 // memory leak reports from wxWin memory tracking code
420 void wxLog::RemoveTraceMask(const wxString
& str
)
422 int index
= ms_aTraceMasks
.Index(str
);
423 if ( index
!= wxNOT_FOUND
)
424 ms_aTraceMasks
.Remove((size_t)index
);
427 void wxLog::ClearTraceMasks()
429 ms_aTraceMasks
.Clear();
432 void wxLog::TimeStamp(wxString
*str
)
438 (void)time(&timeNow
);
439 wxStrftime(buf
, WXSIZEOF(buf
), ms_timestamp
, localtime(&timeNow
));
442 *str
<< buf
<< wxT(": ");
446 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
449 case wxLOG_FatalError
:
450 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
451 DoLogString(_("Program aborted."), t
);
457 DoLogString(wxString(_("Error: ")) + szString
, t
);
461 DoLogString(wxString(_("Warning: ")) + szString
, t
);
468 default: // log unknown log levels too
469 DoLogString(szString
, t
);
476 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
486 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
488 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
493 // nothing to do here
496 // ----------------------------------------------------------------------------
497 // wxLogStderr class implementation
498 // ----------------------------------------------------------------------------
500 wxLogStderr::wxLogStderr(FILE *fp
)
508 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
514 fputs(str
.mb_str(), m_fp
);
515 fputc(_T('\n'), m_fp
);
518 // under GUI systems such as Windows or Mac, programs usually don't have
519 // stderr at all, so show the messages also somewhere else, typically in
520 // the debugger window so that they go at least somewhere instead of being
522 if ( m_fp
== stderr
)
524 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
525 if ( traits
&& !traits
->HasStderr() )
527 wxMessageOutputDebug().Printf(_T("%s"), str
.c_str());
532 // ----------------------------------------------------------------------------
533 // wxLogStream implementation
534 // ----------------------------------------------------------------------------
536 #if wxUSE_STD_IOSTREAM
537 #include "wx/ioswrap.h"
538 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
541 m_ostr
= &wxSTD cerr
;
546 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
550 (*m_ostr
) << str
<< wxConvertWX2MB(szString
) << wxSTD endl
;
552 #endif // wxUSE_STD_IOSTREAM
554 // ----------------------------------------------------------------------------
556 // ----------------------------------------------------------------------------
558 wxLogChain::wxLogChain(wxLog
*logger
)
560 m_bPassMessages
= TRUE
;
563 m_logOld
= wxLog::SetActiveTarget(this);
566 wxLogChain::~wxLogChain()
570 if ( m_logNew
!= this )
574 void wxLogChain::SetLog(wxLog
*logger
)
576 if ( m_logNew
!= this )
582 void wxLogChain::Flush()
587 // be careful to avoid infinite recursion
588 if ( m_logNew
&& m_logNew
!= this )
592 void wxLogChain::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
594 // let the previous logger show it
595 if ( m_logOld
&& IsPassingMessages() )
597 // bogus cast just to access protected DoLog
598 ((wxLogChain
*)m_logOld
)->DoLog(level
, szString
, t
);
601 if ( m_logNew
&& m_logNew
!= this )
604 ((wxLogChain
*)m_logNew
)->DoLog(level
, szString
, t
);
608 // ----------------------------------------------------------------------------
610 // ----------------------------------------------------------------------------
613 // "'this' : used in base member initializer list" - so what?
614 #pragma warning(disable:4355)
617 wxLogPassThrough::wxLogPassThrough()
623 #pragma warning(default:4355)
626 // ============================================================================
627 // Global functions/variables
628 // ============================================================================
630 // ----------------------------------------------------------------------------
632 // ----------------------------------------------------------------------------
634 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
635 bool wxLog::ms_doLog
= TRUE
;
636 bool wxLog::ms_bAutoCreate
= TRUE
;
637 bool wxLog::ms_bVerbose
= FALSE
;
639 wxLogLevel
wxLog::ms_logLevel
= wxLOG_Max
; // log everything by default
641 size_t wxLog::ms_suspendCount
= 0;
643 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
645 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
646 wxArrayString
wxLog::ms_aTraceMasks
;
648 // ----------------------------------------------------------------------------
649 // stdout error logging helper
650 // ----------------------------------------------------------------------------
652 // helper function: wraps the message and justifies it under given position
653 // (looks more pretty on the terminal). Also adds newline at the end.
655 // TODO this is now disabled until I find a portable way of determining the
656 // terminal window size (ok, I found it but does anybody really cares?)
657 #ifdef LOG_PRETTY_WRAP
658 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
660 size_t nMax
= 80; // FIXME
661 size_t nStart
= strlen(pszPrefix
);
665 while ( *psz
!= '\0' ) {
666 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
670 if ( *psz
!= '\0' ) {
672 for ( n
= 0; n
< nStart
; n
++ )
675 // as we wrapped, squeeze all white space
676 while ( isspace(*psz
) )
683 #endif //LOG_PRETTY_WRAP
685 // ----------------------------------------------------------------------------
686 // error code/error message retrieval functions
687 // ----------------------------------------------------------------------------
689 // get error code from syste
690 unsigned long wxSysErrorCode()
692 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
694 return ::GetLastError();
696 // TODO what to do on Windows 3.1?
704 // get error message from system
705 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
708 nErrCode
= wxSysErrorCode();
710 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
712 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
714 // get error message from system
716 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
718 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
722 // copy it to our buffer and free memory
723 if( lpMsgBuf
!= 0 ) {
724 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
725 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
729 // returned string is capitalized and ended with '\r\n' - bad
730 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
731 size_t len
= wxStrlen(s_szBuf
);
734 if ( s_szBuf
[len
- 2] == wxT('\r') )
735 s_szBuf
[len
- 2] = wxT('\0');
739 s_szBuf
[0] = wxT('\0');
749 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
750 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
753 return strerror((int)nErrCode
);