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"
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
55 #if defined(__WINDOWS__)
56 #include "wx/msw/private.h" // includes windows.h
59 // ----------------------------------------------------------------------------
60 // non member functions
61 // ----------------------------------------------------------------------------
63 // define this to enable wrapping of log messages
64 //#define LOG_PRETTY_WRAP
66 #ifdef LOG_PRETTY_WRAP
67 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
70 // ============================================================================
72 // ============================================================================
74 // ----------------------------------------------------------------------------
76 // ----------------------------------------------------------------------------
78 // log functions can't allocate memory (LogError("out of memory...") should
79 // work!), so we use a static buffer for all log messages
80 #define LOG_BUFFER_SIZE (4096)
82 // static buffer for error messages
83 static wxChar s_szBufStatic
[LOG_BUFFER_SIZE
];
85 static wxChar
*s_szBuf
= s_szBufStatic
;
86 static size_t s_szBufSize
= WXSIZEOF( s_szBufStatic
);
90 // the critical section protecting the static buffer
91 static wxCriticalSection gs_csLogBuf
;
93 #endif // wxUSE_THREADS
95 // return true if we have a non NULL non disabled log target
96 static inline bool IsLoggingEnabled()
98 return wxLog::IsEnabled() && (wxLog::GetActiveTarget() != NULL
);
101 // ----------------------------------------------------------------------------
102 // implementation of Log functions
104 // NB: unfortunately we need all these distinct functions, we can't make them
105 // macros and not all compilers inline vararg functions.
106 // ----------------------------------------------------------------------------
108 // wrapper for wxVsnprintf(s_szBuf) which always NULL-terminates it
109 static inline void PrintfInLogBug(const wxChar
*szFormat
, va_list argptr
)
111 if ( wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
) < 0 )
113 // must NUL-terminate it manually
114 s_szBuf
[s_szBufSize
- 1] = _T('\0');
116 //else: NUL-terminated by vsnprintf()
119 // generic log function
120 void wxVLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, va_list argptr
)
122 if ( IsLoggingEnabled() ) {
123 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
125 PrintfInLogBug(szFormat
, argptr
);
127 wxLog::OnLog(level
, s_szBuf
, time(NULL
));
131 void wxLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, ...)
134 va_start(argptr
, szFormat
);
135 wxVLogGeneric(level
, szFormat
, argptr
);
139 #define IMPLEMENT_LOG_FUNCTION(level) \
140 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
142 if ( IsLoggingEnabled() ) { \
143 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
145 PrintfInLogBug(szFormat, argptr); \
147 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
151 void wxLog##level(const wxChar *szFormat, ...) \
154 va_start(argptr, szFormat); \
155 wxVLog##level(szFormat, argptr); \
159 IMPLEMENT_LOG_FUNCTION(Error
)
160 IMPLEMENT_LOG_FUNCTION(Warning
)
161 IMPLEMENT_LOG_FUNCTION(Message
)
162 IMPLEMENT_LOG_FUNCTION(Info
)
163 IMPLEMENT_LOG_FUNCTION(Status
)
165 void wxSafeShowMessage(const wxString
& title
, const wxString
& text
)
168 ::MessageBox(NULL
, text
, title
, MB_OK
| MB_ICONSTOP
);
170 wxFprintf(stderr
, _T("%s: %s\n"), title
.c_str(), text
.c_str());
174 // fatal errors can't be suppressed nor handled by the custom log target and
175 // always terminate the program
176 void wxVLogFatalError(const wxChar
*szFormat
, va_list argptr
)
178 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
180 wxSafeShowMessage(_T("Fatal Error"), s_szBuf
);
185 void wxLogFatalError(const wxChar
*szFormat
, ...)
188 va_start(argptr
, szFormat
);
189 wxVLogFatalError(szFormat
, argptr
);
193 // same as info, but only if 'verbose' mode is on
194 void wxVLogVerbose(const wxChar
*szFormat
, va_list argptr
)
196 if ( IsLoggingEnabled() ) {
197 wxLog
*pLog
= wxLog::GetActiveTarget();
198 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
199 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
201 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
203 wxLog::OnLog(wxLOG_Info
, s_szBuf
, time(NULL
));
208 void wxLogVerbose(const wxChar
*szFormat
, ...)
211 va_start(argptr
, szFormat
);
212 wxVLogVerbose(szFormat
, argptr
);
218 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
219 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
221 if ( IsLoggingEnabled() ) { \
222 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
224 wxVsnprintf(s_szBuf, s_szBufSize, szFormat, argptr); \
226 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
229 void wxLog##level(const wxChar *szFormat, ...) \
232 va_start(argptr, szFormat); \
233 wxVLog##level(szFormat, argptr); \
237 void wxVLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, va_list argptr
)
239 if ( IsLoggingEnabled() && wxLog::IsAllowedTraceMask(mask
) ) {
240 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
243 size_t len
= s_szBufSize
;
244 wxStrncpy(s_szBuf
, _T("("), len
);
245 len
-= 1; // strlen("(")
247 wxStrncat(p
, mask
, len
);
248 size_t lenMask
= wxStrlen(mask
);
252 wxStrncat(p
, _T(") "), len
);
256 wxVsnprintf(p
, len
, szFormat
, argptr
);
258 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
262 void wxLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, ...)
265 va_start(argptr
, szFormat
);
266 wxVLogTrace(mask
, szFormat
, argptr
);
270 void wxVLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, va_list argptr
)
272 // we check that all of mask bits are set in the current mask, so
273 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
274 // if both bits are set.
275 if ( IsLoggingEnabled() && ((wxLog::GetTraceMask() & mask
) == mask
) ) {
276 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
278 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
280 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
284 void wxLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, ...)
287 va_start(argptr
, szFormat
);
288 wxVLogTrace(mask
, szFormat
, argptr
);
293 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
296 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
297 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
299 // wxLogSysError: one uses the last error code, for other you must give it
302 // common part of both wxLogSysError
303 void wxLogSysErrorHelper(long lErrCode
)
305 wxChar szErrMsg
[LOG_BUFFER_SIZE
/ 2];
306 wxSnprintf(szErrMsg
, WXSIZEOF(szErrMsg
),
307 _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
308 wxStrncat(s_szBuf
, szErrMsg
, s_szBufSize
- wxStrlen(s_szBuf
));
310 wxLog::OnLog(wxLOG_Error
, s_szBuf
, time(NULL
));
313 void WXDLLEXPORT
wxVLogSysError(const wxChar
*szFormat
, va_list argptr
)
315 if ( IsLoggingEnabled() ) {
316 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
318 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
320 wxLogSysErrorHelper(wxSysErrorCode());
324 void WXDLLEXPORT
wxLogSysError(const wxChar
*szFormat
, ...)
327 va_start(argptr
, szFormat
);
328 wxVLogSysError(szFormat
, argptr
);
332 void WXDLLEXPORT
wxVLogSysError(long lErrCode
, const wxChar
*szFormat
, va_list argptr
)
334 if ( IsLoggingEnabled() ) {
335 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
337 wxVsnprintf(s_szBuf
, s_szBufSize
, szFormat
, argptr
);
339 wxLogSysErrorHelper(lErrCode
);
343 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const wxChar
*szFormat
, ...)
346 va_start(argptr
, szFormat
);
347 wxVLogSysError(lErrCode
, szFormat
, argptr
);
351 // ----------------------------------------------------------------------------
352 // wxLog class implementation
353 // ----------------------------------------------------------------------------
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
);
462 DoLogString(wxString(_("Error: ")) + szString
, t
);
466 DoLogString(wxString(_("Warning: ")) + szString
, t
);
473 default: // log unknown log levels too
474 DoLogString(szString
, t
);
481 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
491 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
493 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
498 // nothing to do here
501 /*static*/ bool wxLog::IsAllowedTraceMask(const wxChar
*mask
)
503 for ( wxArrayString::iterator it
= ms_aTraceMasks
.begin(),
504 en
= ms_aTraceMasks
.end();
511 // ----------------------------------------------------------------------------
512 // wxLogStderr class implementation
513 // ----------------------------------------------------------------------------
515 wxLogStderr::wxLogStderr(FILE *fp
)
523 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
529 fputs(str
.mb_str(), m_fp
);
530 fputc(_T('\n'), m_fp
);
533 // under GUI systems such as Windows or Mac, programs usually don't have
534 // stderr at all, so show the messages also somewhere else, typically in
535 // the debugger window so that they go at least somewhere instead of being
537 if ( m_fp
== stderr
)
539 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
540 if ( traits
&& !traits
->HasStderr() )
542 wxMessageOutputDebug().Printf(_T("%s"), str
.c_str());
547 // ----------------------------------------------------------------------------
548 // wxLogStream implementation
549 // ----------------------------------------------------------------------------
551 #if wxUSE_STD_IOSTREAM
552 #include "wx/ioswrap.h"
553 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
556 m_ostr
= &wxSTD cerr
;
561 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
565 (*m_ostr
) << str
<< wxConvertWX2MB(szString
) << wxSTD endl
;
567 #endif // wxUSE_STD_IOSTREAM
569 // ----------------------------------------------------------------------------
571 // ----------------------------------------------------------------------------
573 wxLogChain::wxLogChain(wxLog
*logger
)
575 m_bPassMessages
= TRUE
;
578 m_logOld
= wxLog::SetActiveTarget(this);
581 wxLogChain::~wxLogChain()
585 if ( m_logNew
!= this )
589 void wxLogChain::SetLog(wxLog
*logger
)
591 if ( m_logNew
!= this )
597 void wxLogChain::Flush()
602 // be careful to avoid infinite recursion
603 if ( m_logNew
&& m_logNew
!= this )
607 void wxLogChain::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
609 // let the previous logger show it
610 if ( m_logOld
&& IsPassingMessages() )
612 // bogus cast just to access protected DoLog
613 ((wxLogChain
*)m_logOld
)->DoLog(level
, szString
, t
);
616 if ( m_logNew
&& m_logNew
!= this )
619 ((wxLogChain
*)m_logNew
)->DoLog(level
, szString
, t
);
623 // ----------------------------------------------------------------------------
625 // ----------------------------------------------------------------------------
628 // "'this' : used in base member initializer list" - so what?
629 #pragma warning(disable:4355)
632 wxLogPassThrough::wxLogPassThrough()
638 #pragma warning(default:4355)
641 // ============================================================================
642 // Global functions/variables
643 // ============================================================================
645 // ----------------------------------------------------------------------------
647 // ----------------------------------------------------------------------------
649 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
650 bool wxLog::ms_doLog
= TRUE
;
651 bool wxLog::ms_bAutoCreate
= TRUE
;
652 bool wxLog::ms_bVerbose
= FALSE
;
654 wxLogLevel
wxLog::ms_logLevel
= wxLOG_Max
; // log everything by default
656 size_t wxLog::ms_suspendCount
= 0;
658 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
660 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
661 wxArrayString
wxLog::ms_aTraceMasks
;
663 // ----------------------------------------------------------------------------
664 // stdout error logging helper
665 // ----------------------------------------------------------------------------
667 // helper function: wraps the message and justifies it under given position
668 // (looks more pretty on the terminal). Also adds newline at the end.
670 // TODO this is now disabled until I find a portable way of determining the
671 // terminal window size (ok, I found it but does anybody really cares?)
672 #ifdef LOG_PRETTY_WRAP
673 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
675 size_t nMax
= 80; // FIXME
676 size_t nStart
= strlen(pszPrefix
);
680 while ( *psz
!= '\0' ) {
681 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
685 if ( *psz
!= '\0' ) {
687 for ( n
= 0; n
< nStart
; n
++ )
690 // as we wrapped, squeeze all white space
691 while ( isspace(*psz
) )
698 #endif //LOG_PRETTY_WRAP
700 // ----------------------------------------------------------------------------
701 // error code/error message retrieval functions
702 // ----------------------------------------------------------------------------
704 // get error code from syste
705 unsigned long wxSysErrorCode()
707 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
709 return ::GetLastError();
711 // TODO what to do on Windows 3.1?
719 // get error message from system
720 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
723 nErrCode
= wxSysErrorCode();
725 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
727 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
729 // get error message from system
731 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
733 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
737 // copy it to our buffer and free memory
738 if( lpMsgBuf
!= 0 ) {
739 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
740 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
744 // returned string is capitalized and ended with '\r\n' - bad
745 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
746 size_t len
= wxStrlen(s_szBuf
);
749 if ( s_szBuf
[len
- 2] == wxT('\r') )
750 s_szBuf
[len
- 2] = wxT('\0');
754 s_szBuf
[0] = wxT('\0');
764 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
765 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
768 return strerror((int)nErrCode
);