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 #if defined(__WINDOWS__)
55 #include "wx/msw/private.h" // includes windows.h
58 // ----------------------------------------------------------------------------
59 // non member functions
60 // ----------------------------------------------------------------------------
62 // define this to enable wrapping of log messages
63 //#define LOG_PRETTY_WRAP
65 #ifdef LOG_PRETTY_WRAP
66 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
69 // ============================================================================
71 // ============================================================================
73 // ----------------------------------------------------------------------------
75 // ----------------------------------------------------------------------------
77 // log functions can't allocate memory (LogError("out of memory...") should
78 // work!), so we use a static buffer for all log messages
79 #define LOG_BUFFER_SIZE (4096)
81 // static buffer for error messages
82 static wxChar s_szBufStatic
[LOG_BUFFER_SIZE
];
84 static wxChar
*s_szBuf
= s_szBufStatic
;
85 static size_t s_szBufSize
= WXSIZEOF( s_szBufStatic
);
89 // the critical section protecting the static buffer
90 static wxCriticalSection gs_csLogBuf
;
92 #endif // wxUSE_THREADS
94 // return true if we have a non NULL non disabled log target
95 static inline bool IsLoggingEnabled()
97 return wxLog::IsEnabled() && (wxLog::GetActiveTarget() != NULL
);
100 // ----------------------------------------------------------------------------
101 // implementation of Log functions
103 // NB: unfortunately we need all these distinct functions, we can't make them
104 // macros and not all compilers inline vararg functions.
105 // ----------------------------------------------------------------------------
107 // wrapper for wxVsnprintf(s_szBuf) which always NULL-terminates it
108 static inline void PrintfInLogBug(const wxChar
*szFormat
, va_list argptr
)
110 if ( wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
) < 0 )
112 // must NUL-terminate it manually
113 s_szBuf
[s_szBufSize
- 1] = _T('\0');
115 //else: NUL-terminated by vsnprintf()
118 // generic log function
119 void wxVLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, va_list argptr
)
121 if ( IsLoggingEnabled() ) {
122 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
124 PrintfInLogBug(szFormat
, argptr
);
126 wxLog::OnLog(level
, s_szBuf
, time(NULL
));
130 void wxLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, ...)
133 va_start(argptr
, szFormat
);
134 wxVLogGeneric(level
, szFormat
, argptr
);
138 #define IMPLEMENT_LOG_FUNCTION(level) \
139 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
141 if ( IsLoggingEnabled() ) { \
142 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
144 PrintfInLogBug(szFormat, argptr); \
146 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
150 void wxLog##level(const wxChar *szFormat, ...) \
153 va_start(argptr, szFormat); \
154 wxVLog##level(szFormat, argptr); \
158 IMPLEMENT_LOG_FUNCTION(Error
)
159 IMPLEMENT_LOG_FUNCTION(Warning
)
160 IMPLEMENT_LOG_FUNCTION(Message
)
161 IMPLEMENT_LOG_FUNCTION(Info
)
162 IMPLEMENT_LOG_FUNCTION(Status
)
164 void wxSafeShowMessage(const wxString
& title
, const wxString
& text
)
167 ::MessageBox(NULL
, text
, title
, MB_OK
| MB_ICONSTOP
);
169 wxFprintf(stderr
, _T("%s: %s\n"), title
.c_str(), text
.c_str());
173 // fatal errors can't be suppressed nor handled by the custom log target and
174 // always terminate the program
175 void wxVLogFatalError(const wxChar
*szFormat
, va_list argptr
)
177 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
179 wxSafeShowMessage(_T("Fatal Error"), s_szBuf
);
184 void wxLogFatalError(const wxChar
*szFormat
, ...)
187 va_start(argptr
, szFormat
);
188 wxVLogFatalError(szFormat
, argptr
);
192 // same as info, but only if 'verbose' mode is on
193 void wxVLogVerbose(const wxChar
*szFormat
, va_list argptr
)
195 if ( IsLoggingEnabled() ) {
196 wxLog
*pLog
= wxLog::GetActiveTarget();
197 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
198 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
200 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
202 wxLog::OnLog(wxLOG_Info
, s_szBuf
, time(NULL
));
207 void wxLogVerbose(const wxChar
*szFormat
, ...)
210 va_start(argptr
, szFormat
);
211 wxVLogVerbose(szFormat
, argptr
);
217 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
218 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
220 if ( IsLoggingEnabled() ) { \
221 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
223 wxVsnprintf(s_szBuf, s_szBufSize, szFormat, argptr); \
225 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
228 void wxLog##level(const wxChar *szFormat, ...) \
231 va_start(argptr, szFormat); \
232 wxVLog##level(szFormat, argptr); \
236 void wxVLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, va_list argptr
)
238 if ( IsLoggingEnabled() && wxLog::IsAllowedTraceMask(mask
) ) {
239 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
242 size_t len
= s_szBufSize
;
243 wxStrncpy(s_szBuf
, _T("("), len
);
244 len
-= 1; // strlen("(")
246 wxStrncat(p
, mask
, len
);
247 size_t lenMask
= wxStrlen(mask
);
251 wxStrncat(p
, _T(") "), len
);
255 wxVsnprintf(p
, len
, szFormat
, argptr
);
257 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
261 void wxLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, ...)
264 va_start(argptr
, szFormat
);
265 wxVLogTrace(mask
, szFormat
, argptr
);
269 void wxVLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, va_list argptr
)
271 // we check that all of mask bits are set in the current mask, so
272 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
273 // if both bits are set.
274 if ( IsLoggingEnabled() && ((wxLog::GetTraceMask() & mask
) == mask
) ) {
275 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
277 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
279 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
283 void wxLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, ...)
286 va_start(argptr
, szFormat
);
287 wxVLogTrace(mask
, szFormat
, argptr
);
292 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
295 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
296 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
298 // wxLogSysError: one uses the last error code, for other you must give it
301 // common part of both wxLogSysError
302 void wxLogSysErrorHelper(long lErrCode
)
304 wxChar szErrMsg
[LOG_BUFFER_SIZE
/ 2];
305 wxSnprintf(szErrMsg
, WXSIZEOF(szErrMsg
),
306 _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
307 wxStrncat(s_szBuf
, szErrMsg
, s_szBufSize
- wxStrlen(s_szBuf
));
309 wxLog::OnLog(wxLOG_Error
, s_szBuf
, time(NULL
));
312 void WXDLLEXPORT
wxVLogSysError(const wxChar
*szFormat
, va_list argptr
)
314 if ( IsLoggingEnabled() ) {
315 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
317 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
319 wxLogSysErrorHelper(wxSysErrorCode());
323 void WXDLLEXPORT
wxLogSysError(const wxChar
*szFormat
, ...)
326 va_start(argptr
, szFormat
);
327 wxVLogSysError(szFormat
, argptr
);
331 void WXDLLEXPORT
wxVLogSysError(long lErrCode
, const wxChar
*szFormat
, va_list argptr
)
333 if ( IsLoggingEnabled() ) {
334 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
336 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
338 wxLogSysErrorHelper(lErrCode
);
342 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const wxChar
*szFormat
, ...)
345 va_start(argptr
, szFormat
);
346 wxVLogSysError(lErrCode
, szFormat
, argptr
);
350 // ----------------------------------------------------------------------------
351 // wxLog class implementation
352 // ----------------------------------------------------------------------------
358 wxChar
*wxLog::SetLogBuffer( wxChar
*buf
, size_t size
)
360 wxChar
*oldbuf
= s_szBuf
;
364 s_szBuf
= s_szBufStatic
;
365 s_szBufSize
= WXSIZEOF( s_szBufStatic
);
373 return (oldbuf
== s_szBufStatic
) ? 0 : oldbuf
;
376 wxLog
*wxLog::GetActiveTarget()
378 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
379 // prevent infinite recursion if someone calls wxLogXXX() from
380 // wxApp::CreateLogTarget()
381 static bool s_bInGetActiveTarget
= FALSE
;
382 if ( !s_bInGetActiveTarget
) {
383 s_bInGetActiveTarget
= TRUE
;
385 // ask the application to create a log target for us
386 if ( wxTheApp
!= NULL
)
387 ms_pLogger
= wxTheApp
->CreateLogTarget();
389 ms_pLogger
= new wxLogStderr
;
391 s_bInGetActiveTarget
= FALSE
;
393 // do nothing if it fails - what can we do?
400 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
402 if ( ms_pLogger
!= NULL
) {
403 // flush the old messages before changing because otherwise they might
404 // get lost later if this target is not restored
408 wxLog
*pOldLogger
= ms_pLogger
;
409 ms_pLogger
= pLogger
;
414 void wxLog::DontCreateOnDemand()
416 ms_bAutoCreate
= FALSE
;
418 // this is usually called at the end of the program and we assume that it
419 // is *always* called at the end - so we free memory here to avoid false
420 // memory leak reports from wxWin memory tracking code
424 void wxLog::RemoveTraceMask(const wxString
& str
)
426 int index
= ms_aTraceMasks
.Index(str
);
427 if ( index
!= wxNOT_FOUND
)
428 ms_aTraceMasks
.Remove((size_t)index
);
431 void wxLog::ClearTraceMasks()
433 ms_aTraceMasks
.Clear();
436 void wxLog::TimeStamp(wxString
*str
)
442 (void)time(&timeNow
);
443 wxStrftime(buf
, WXSIZEOF(buf
), ms_timestamp
, localtime(&timeNow
));
446 *str
<< buf
<< wxT(": ");
450 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
453 case wxLOG_FatalError
:
454 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
455 DoLogString(_("Program aborted."), t
);
461 DoLogString(wxString(_("Error: ")) + szString
, t
);
465 DoLogString(wxString(_("Warning: ")) + szString
, t
);
472 default: // log unknown log levels too
473 DoLogString(szString
, t
);
480 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
490 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
492 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
497 // nothing to do here
500 // ----------------------------------------------------------------------------
501 // wxLogStderr class implementation
502 // ----------------------------------------------------------------------------
504 wxLogStderr::wxLogStderr(FILE *fp
)
512 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
518 fputs(str
.mb_str(), m_fp
);
519 fputc(_T('\n'), m_fp
);
522 // under GUI systems such as Windows or Mac, programs usually don't have
523 // stderr at all, so show the messages also somewhere else, typically in
524 // the debugger window so that they go at least somewhere instead of being
526 if ( m_fp
== stderr
)
528 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
529 if ( traits
&& !traits
->HasStderr() )
531 wxMessageOutputDebug().Printf(_T("%s"), str
.c_str());
536 // ----------------------------------------------------------------------------
537 // wxLogStream implementation
538 // ----------------------------------------------------------------------------
540 #if wxUSE_STD_IOSTREAM
541 #include "wx/ioswrap.h"
542 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
545 m_ostr
= &wxSTD cerr
;
550 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
554 (*m_ostr
) << str
<< wxConvertWX2MB(szString
) << wxSTD endl
;
556 #endif // wxUSE_STD_IOSTREAM
558 // ----------------------------------------------------------------------------
560 // ----------------------------------------------------------------------------
562 wxLogChain::wxLogChain(wxLog
*logger
)
564 m_bPassMessages
= TRUE
;
567 m_logOld
= wxLog::SetActiveTarget(this);
570 wxLogChain::~wxLogChain()
574 if ( m_logNew
!= this )
578 void wxLogChain::SetLog(wxLog
*logger
)
580 if ( m_logNew
!= this )
586 void wxLogChain::Flush()
591 // be careful to avoid infinite recursion
592 if ( m_logNew
&& m_logNew
!= this )
596 void wxLogChain::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
598 // let the previous logger show it
599 if ( m_logOld
&& IsPassingMessages() )
601 // bogus cast just to access protected DoLog
602 ((wxLogChain
*)m_logOld
)->DoLog(level
, szString
, t
);
605 if ( m_logNew
&& m_logNew
!= this )
608 ((wxLogChain
*)m_logNew
)->DoLog(level
, szString
, t
);
612 // ----------------------------------------------------------------------------
614 // ----------------------------------------------------------------------------
617 // "'this' : used in base member initializer list" - so what?
618 #pragma warning(disable:4355)
621 wxLogPassThrough::wxLogPassThrough()
627 #pragma warning(default:4355)
630 // ============================================================================
631 // Global functions/variables
632 // ============================================================================
634 // ----------------------------------------------------------------------------
636 // ----------------------------------------------------------------------------
638 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
639 bool wxLog::ms_doLog
= TRUE
;
640 bool wxLog::ms_bAutoCreate
= TRUE
;
641 bool wxLog::ms_bVerbose
= FALSE
;
643 wxLogLevel
wxLog::ms_logLevel
= wxLOG_Max
; // log everything by default
645 size_t wxLog::ms_suspendCount
= 0;
647 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
649 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
650 wxArrayString
wxLog::ms_aTraceMasks
;
652 // ----------------------------------------------------------------------------
653 // stdout error logging helper
654 // ----------------------------------------------------------------------------
656 // helper function: wraps the message and justifies it under given position
657 // (looks more pretty on the terminal). Also adds newline at the end.
659 // TODO this is now disabled until I find a portable way of determining the
660 // terminal window size (ok, I found it but does anybody really cares?)
661 #ifdef LOG_PRETTY_WRAP
662 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
664 size_t nMax
= 80; // FIXME
665 size_t nStart
= strlen(pszPrefix
);
669 while ( *psz
!= '\0' ) {
670 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
674 if ( *psz
!= '\0' ) {
676 for ( n
= 0; n
< nStart
; n
++ )
679 // as we wrapped, squeeze all white space
680 while ( isspace(*psz
) )
687 #endif //LOG_PRETTY_WRAP
689 // ----------------------------------------------------------------------------
690 // error code/error message retrieval functions
691 // ----------------------------------------------------------------------------
693 // get error code from syste
694 unsigned long wxSysErrorCode()
696 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
698 return ::GetLastError();
700 // TODO what to do on Windows 3.1?
708 // get error message from system
709 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
712 nErrCode
= wxSysErrorCode();
714 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
716 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
718 // get error message from system
720 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
722 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
726 // copy it to our buffer and free memory
727 if( lpMsgBuf
!= 0 ) {
728 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
729 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
733 // returned string is capitalized and ended with '\r\n' - bad
734 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
735 size_t len
= wxStrlen(s_szBuf
);
738 if ( s_szBuf
[len
- 2] == wxT('\r') )
739 s_szBuf
[len
- 2] = wxT('\0');
743 s_szBuf
[0] = wxT('\0');
753 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
754 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
757 return strerror((int)nErrCode
);