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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
21 #pragma implementation "log.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
36 #include "wx/arrstr.h"
38 #include "wx/string.h"
41 #include "wx/apptrait.h"
44 #include "wx/msgout.h"
45 #include "wx/textfile.h"
46 #include "wx/thread.h"
48 #include "wx/wxchar.h"
50 // other standard headers
60 #include "wx/msw/wince/time.h"
63 #if defined(__WINDOWS__)
64 #include "wx/msw/private.h" // includes windows.h
67 // ----------------------------------------------------------------------------
68 // non member functions
69 // ----------------------------------------------------------------------------
71 // define this to enable wrapping of log messages
72 //#define LOG_PRETTY_WRAP
74 #ifdef LOG_PRETTY_WRAP
75 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
78 // ============================================================================
80 // ============================================================================
82 // ----------------------------------------------------------------------------
84 // ----------------------------------------------------------------------------
86 // log functions can't allocate memory (LogError("out of memory...") should
87 // work!), so we use a static buffer for all log messages
88 #define LOG_BUFFER_SIZE (4096)
90 // static buffer for error messages
91 static wxChar s_szBufStatic
[LOG_BUFFER_SIZE
];
93 static wxChar
*s_szBuf
= s_szBufStatic
;
94 static size_t s_szBufSize
= WXSIZEOF( s_szBufStatic
);
98 // the critical section protecting the static buffer
99 static wxCriticalSection gs_csLogBuf
;
101 #endif // wxUSE_THREADS
103 // return true if we have a non NULL non disabled log target
104 static inline bool IsLoggingEnabled()
106 return wxLog::IsEnabled() && (wxLog::GetActiveTarget() != NULL
);
109 // ----------------------------------------------------------------------------
110 // implementation of Log functions
112 // NB: unfortunately we need all these distinct functions, we can't make them
113 // macros and not all compilers inline vararg functions.
114 // ----------------------------------------------------------------------------
116 // wrapper for wxVsnprintf(s_szBuf) which always NULL-terminates it
117 static inline void PrintfInLogBug(const wxChar
*szFormat
, va_list argptr
)
119 if ( wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
) < 0 )
121 // must NUL-terminate it manually
122 s_szBuf
[s_szBufSize
- 1] = _T('\0');
124 //else: NUL-terminated by vsnprintf()
127 // generic log function
128 void wxVLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, va_list argptr
)
130 if ( IsLoggingEnabled() ) {
131 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
133 PrintfInLogBug(szFormat
, argptr
);
135 wxLog::OnLog(level
, s_szBuf
, time(NULL
));
139 void wxLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, ...)
142 va_start(argptr
, szFormat
);
143 wxVLogGeneric(level
, szFormat
, argptr
);
147 #define IMPLEMENT_LOG_FUNCTION(level) \
148 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
150 if ( IsLoggingEnabled() ) { \
151 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
153 PrintfInLogBug(szFormat, argptr); \
155 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
159 void wxLog##level(const wxChar *szFormat, ...) \
162 va_start(argptr, szFormat); \
163 wxVLog##level(szFormat, argptr); \
167 IMPLEMENT_LOG_FUNCTION(Error
)
168 IMPLEMENT_LOG_FUNCTION(Warning
)
169 IMPLEMENT_LOG_FUNCTION(Message
)
170 IMPLEMENT_LOG_FUNCTION(Info
)
171 IMPLEMENT_LOG_FUNCTION(Status
)
173 void wxSafeShowMessage(const wxString
& title
, const wxString
& text
)
176 ::MessageBox(NULL
, text
, title
, MB_OK
| MB_ICONSTOP
);
178 wxFprintf(stderr
, _T("%s: %s\n"), title
.c_str(), text
.c_str());
182 // fatal errors can't be suppressed nor handled by the custom log target and
183 // always terminate the program
184 void wxVLogFatalError(const wxChar
*szFormat
, va_list argptr
)
186 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
188 wxSafeShowMessage(_T("Fatal Error"), s_szBuf
);
197 void wxLogFatalError(const wxChar
*szFormat
, ...)
200 va_start(argptr
, szFormat
);
201 wxVLogFatalError(szFormat
, argptr
);
205 // same as info, but only if 'verbose' mode is on
206 void wxVLogVerbose(const wxChar
*szFormat
, va_list argptr
)
208 if ( IsLoggingEnabled() ) {
209 wxLog
*pLog
= wxLog::GetActiveTarget();
210 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
211 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
213 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
215 wxLog::OnLog(wxLOG_Info
, s_szBuf
, time(NULL
));
220 void wxLogVerbose(const wxChar
*szFormat
, ...)
223 va_start(argptr
, szFormat
);
224 wxVLogVerbose(szFormat
, argptr
);
230 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
231 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
233 if ( IsLoggingEnabled() ) { \
234 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
236 wxVsnprintf(s_szBuf, s_szBufSize, szFormat, argptr); \
238 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
241 void wxLog##level(const wxChar *szFormat, ...) \
244 va_start(argptr, szFormat); \
245 wxVLog##level(szFormat, argptr); \
249 void wxVLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, va_list argptr
)
251 if ( IsLoggingEnabled() && wxLog::IsAllowedTraceMask(mask
) ) {
252 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
255 size_t len
= s_szBufSize
;
256 wxStrncpy(s_szBuf
, _T("("), len
);
257 len
-= 1; // strlen("(")
259 wxStrncat(p
, mask
, len
);
260 size_t lenMask
= wxStrlen(mask
);
264 wxStrncat(p
, _T(") "), len
);
268 wxVsnprintf(p
, len
, szFormat
, argptr
);
270 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
274 void wxLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, ...)
277 va_start(argptr
, szFormat
);
278 wxVLogTrace(mask
, szFormat
, argptr
);
282 void wxVLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, va_list argptr
)
284 // we check that all of mask bits are set in the current mask, so
285 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
286 // if both bits are set.
287 if ( IsLoggingEnabled() && ((wxLog::GetTraceMask() & mask
) == mask
) ) {
288 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
290 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
292 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
296 void wxLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, ...)
299 va_start(argptr
, szFormat
);
300 wxVLogTrace(mask
, szFormat
, argptr
);
305 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
308 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
309 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
311 // wxLogSysError: one uses the last error code, for other you must give it
314 // common part of both wxLogSysError
315 void wxLogSysErrorHelper(long lErrCode
)
317 wxChar szErrMsg
[LOG_BUFFER_SIZE
/ 2];
318 wxSnprintf(szErrMsg
, WXSIZEOF(szErrMsg
),
319 _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
320 wxStrncat(s_szBuf
, szErrMsg
, s_szBufSize
- wxStrlen(s_szBuf
));
322 wxLog::OnLog(wxLOG_Error
, s_szBuf
, time(NULL
));
325 void WXDLLEXPORT
wxVLogSysError(const wxChar
*szFormat
, va_list argptr
)
327 if ( IsLoggingEnabled() ) {
328 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
330 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
332 wxLogSysErrorHelper(wxSysErrorCode());
336 void WXDLLEXPORT
wxLogSysError(const wxChar
*szFormat
, ...)
339 va_start(argptr
, szFormat
);
340 wxVLogSysError(szFormat
, argptr
);
344 void WXDLLEXPORT
wxVLogSysError(long lErrCode
, const wxChar
*szFormat
, va_list argptr
)
346 if ( IsLoggingEnabled() ) {
347 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
349 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
351 wxLogSysErrorHelper(lErrCode
);
355 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const wxChar
*szFormat
, ...)
358 va_start(argptr
, szFormat
);
359 wxVLogSysError(lErrCode
, szFormat
, argptr
);
363 // ----------------------------------------------------------------------------
364 // wxLog class implementation
365 // ----------------------------------------------------------------------------
371 wxChar
*wxLog::SetLogBuffer( wxChar
*buf
, size_t size
)
373 wxChar
*oldbuf
= s_szBuf
;
377 s_szBuf
= s_szBufStatic
;
378 s_szBufSize
= WXSIZEOF( s_szBufStatic
);
386 return (oldbuf
== s_szBufStatic
) ? 0 : oldbuf
;
389 wxLog
*wxLog::GetActiveTarget()
391 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
392 // prevent infinite recursion if someone calls wxLogXXX() from
393 // wxApp::CreateLogTarget()
394 static bool s_bInGetActiveTarget
= FALSE
;
395 if ( !s_bInGetActiveTarget
) {
396 s_bInGetActiveTarget
= TRUE
;
398 // ask the application to create a log target for us
399 if ( wxTheApp
!= NULL
)
400 ms_pLogger
= wxTheApp
->GetTraits()->CreateLogTarget();
402 ms_pLogger
= new wxLogStderr
;
404 s_bInGetActiveTarget
= FALSE
;
406 // do nothing if it fails - what can we do?
413 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
415 if ( ms_pLogger
!= NULL
) {
416 // flush the old messages before changing because otherwise they might
417 // get lost later if this target is not restored
421 wxLog
*pOldLogger
= ms_pLogger
;
422 ms_pLogger
= pLogger
;
427 void wxLog::DontCreateOnDemand()
429 ms_bAutoCreate
= FALSE
;
431 // this is usually called at the end of the program and we assume that it
432 // is *always* called at the end - so we free memory here to avoid false
433 // memory leak reports from wxWin memory tracking code
437 void wxLog::RemoveTraceMask(const wxString
& str
)
439 int index
= ms_aTraceMasks
.Index(str
);
440 if ( index
!= wxNOT_FOUND
)
441 ms_aTraceMasks
.RemoveAt((size_t)index
);
444 void wxLog::ClearTraceMasks()
446 ms_aTraceMasks
.Clear();
449 void wxLog::TimeStamp(wxString
*str
)
455 (void)time(&timeNow
);
456 wxStrftime(buf
, WXSIZEOF(buf
), ms_timestamp
, localtime(&timeNow
));
459 *str
<< buf
<< wxT(": ");
463 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
466 case wxLOG_FatalError
:
467 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
468 DoLogString(_("Program aborted."), t
);
478 DoLogString(wxString(_("Error: ")) + szString
, t
);
482 DoLogString(wxString(_("Warning: ")) + szString
, t
);
489 default: // log unknown log levels too
490 DoLogString(szString
, t
);
497 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
507 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
509 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
514 // nothing to do here
517 /*static*/ bool wxLog::IsAllowedTraceMask(const wxChar
*mask
)
519 for ( wxArrayString::iterator it
= ms_aTraceMasks
.begin(),
520 en
= ms_aTraceMasks
.end();
527 // ----------------------------------------------------------------------------
528 // wxLogStderr class implementation
529 // ----------------------------------------------------------------------------
531 wxLogStderr::wxLogStderr(FILE *fp
)
539 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
545 fputs(str
.mb_str(), m_fp
);
546 fputc(_T('\n'), m_fp
);
549 // under GUI systems such as Windows or Mac, programs usually don't have
550 // stderr at all, so show the messages also somewhere else, typically in
551 // the debugger window so that they go at least somewhere instead of being
553 if ( m_fp
== stderr
)
555 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
556 if ( traits
&& !traits
->HasStderr() )
558 wxMessageOutputDebug().Printf(_T("%s"), str
.c_str());
563 // ----------------------------------------------------------------------------
564 // wxLogStream implementation
565 // ----------------------------------------------------------------------------
567 #if wxUSE_STD_IOSTREAM
568 #include "wx/ioswrap.h"
569 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
572 m_ostr
= &wxSTD cerr
;
577 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
581 (*m_ostr
) << str
<< wxConvertWX2MB(szString
) << wxSTD endl
;
583 #endif // wxUSE_STD_IOSTREAM
585 // ----------------------------------------------------------------------------
587 // ----------------------------------------------------------------------------
589 wxLogChain::wxLogChain(wxLog
*logger
)
591 m_bPassMessages
= TRUE
;
594 m_logOld
= wxLog::SetActiveTarget(this);
597 wxLogChain::~wxLogChain()
601 if ( m_logNew
!= this )
605 void wxLogChain::SetLog(wxLog
*logger
)
607 if ( m_logNew
!= this )
613 void wxLogChain::Flush()
618 // be careful to avoid infinite recursion
619 if ( m_logNew
&& m_logNew
!= this )
623 void wxLogChain::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
625 // let the previous logger show it
626 if ( m_logOld
&& IsPassingMessages() )
628 // bogus cast just to access protected DoLog
629 ((wxLogChain
*)m_logOld
)->DoLog(level
, szString
, t
);
632 if ( m_logNew
&& m_logNew
!= this )
635 ((wxLogChain
*)m_logNew
)->DoLog(level
, szString
, t
);
639 // ----------------------------------------------------------------------------
641 // ----------------------------------------------------------------------------
644 // "'this' : used in base member initializer list" - so what?
645 #pragma warning(disable:4355)
648 wxLogPassThrough::wxLogPassThrough()
654 #pragma warning(default:4355)
657 // ============================================================================
658 // Global functions/variables
659 // ============================================================================
661 // ----------------------------------------------------------------------------
663 // ----------------------------------------------------------------------------
665 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
666 bool wxLog::ms_doLog
= TRUE
;
667 bool wxLog::ms_bAutoCreate
= TRUE
;
668 bool wxLog::ms_bVerbose
= FALSE
;
670 wxLogLevel
wxLog::ms_logLevel
= wxLOG_Max
; // log everything by default
672 size_t wxLog::ms_suspendCount
= 0;
674 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
676 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
677 wxArrayString
wxLog::ms_aTraceMasks
;
679 // ----------------------------------------------------------------------------
680 // stdout error logging helper
681 // ----------------------------------------------------------------------------
683 // helper function: wraps the message and justifies it under given position
684 // (looks more pretty on the terminal). Also adds newline at the end.
686 // TODO this is now disabled until I find a portable way of determining the
687 // terminal window size (ok, I found it but does anybody really cares?)
688 #ifdef LOG_PRETTY_WRAP
689 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
691 size_t nMax
= 80; // FIXME
692 size_t nStart
= strlen(pszPrefix
);
696 while ( *psz
!= '\0' ) {
697 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
701 if ( *psz
!= '\0' ) {
703 for ( n
= 0; n
< nStart
; n
++ )
706 // as we wrapped, squeeze all white space
707 while ( isspace(*psz
) )
714 #endif //LOG_PRETTY_WRAP
716 // ----------------------------------------------------------------------------
717 // error code/error message retrieval functions
718 // ----------------------------------------------------------------------------
720 // get error code from syste
721 unsigned long wxSysErrorCode()
723 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
725 return ::GetLastError();
727 // TODO what to do on Windows 3.1?
735 // get error message from system
736 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
739 nErrCode
= wxSysErrorCode();
741 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
743 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
745 // get error message from system
747 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
749 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
753 // copy it to our buffer and free memory
754 if( lpMsgBuf
!= 0 ) {
755 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
756 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
760 // returned string is capitalized and ended with '\r\n' - bad
761 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
762 size_t len
= wxStrlen(s_szBuf
);
765 if ( s_szBuf
[len
- 2] == wxT('\r') )
766 s_szBuf
[len
- 2] = wxT('\0');
770 s_szBuf
[0] = wxT('\0');
780 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
781 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
784 return strerror((int)nErrCode
);