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 license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation "log.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
33 #include "wx/string.h"
38 #include "wx/window.h"
39 #include "wx/msgdlg.h"
41 #include "wx/msw/private.h"
47 #include "wx/textfile.h"
49 #include "wx/wxchar.h"
51 #include "wx/thread.h"
55 // other standard headers
60 #if defined(__WXMSW__)
61 #include "wx/msw/private.h" // includes windows.h for OutputDebugString
64 #if defined(__WXMAC__)
65 #include "wx/mac/private.h" // includes mac headers
68 // ----------------------------------------------------------------------------
69 // non member functions
70 // ----------------------------------------------------------------------------
72 // define this to enable wrapping of log messages
73 //#define LOG_PRETTY_WRAP
75 #ifdef LOG_PRETTY_WRAP
76 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
79 // ============================================================================
81 // ============================================================================
83 // ----------------------------------------------------------------------------
85 // ----------------------------------------------------------------------------
87 // log functions can't allocate memory (LogError("out of memory...") should
88 // work!), so we use a static buffer for all log messages
89 #define LOG_BUFFER_SIZE (4096)
91 // static buffer for error messages
92 static wxChar s_szBuf
[LOG_BUFFER_SIZE
];
96 // the critical section protecting the static buffer
97 static wxCriticalSection gs_csLogBuf
;
99 #endif // wxUSE_THREADS
101 // return true if we have a non NULL non disabled log target
102 static inline bool IsLoggingEnabled()
104 return wxLog::IsEnabled() && (wxLog::GetActiveTarget() != NULL
);
107 // ----------------------------------------------------------------------------
108 // implementation of Log functions
110 // NB: unfortunately we need all these distinct functions, we can't make them
111 // macros and not all compilers inline vararg functions.
112 // ----------------------------------------------------------------------------
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 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), 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 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
142 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
145 void wxLog##level(const wxChar *szFormat, ...) \
148 va_start(argptr, szFormat); \
149 wxVLog##level(szFormat, argptr); \
153 IMPLEMENT_LOG_FUNCTION(Error
)
154 IMPLEMENT_LOG_FUNCTION(Warning
)
155 IMPLEMENT_LOG_FUNCTION(Message
)
156 IMPLEMENT_LOG_FUNCTION(Info
)
157 IMPLEMENT_LOG_FUNCTION(Status
)
159 // fatal errors can't be suppressed nor handled by the custom log target and
160 // always terminate the program
161 void wxVLogFatalError(const wxChar
*szFormat
, va_list argptr
)
163 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
166 wxMessageBox(s_szBuf
, _("Fatal Error"), wxID_OK
| wxICON_STOP
);
168 fprintf(stderr
, _("Fatal error: %s\n"), s_szBuf
);
174 void wxLogFatalError(const wxChar
*szFormat
, ...)
177 va_start(argptr
, szFormat
);
178 wxVLogFatalError(szFormat
, argptr
);
182 // same as info, but only if 'verbose' mode is on
183 void wxVLogVerbose(const wxChar
*szFormat
, va_list argptr
)
185 if ( IsLoggingEnabled() ) {
186 wxLog
*pLog
= wxLog::GetActiveTarget();
187 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
188 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
190 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
192 wxLog::OnLog(wxLOG_Info
, s_szBuf
, time(NULL
));
197 void wxLogVerbose(const wxChar
*szFormat
, ...)
200 va_start(argptr
, szFormat
);
201 wxVLogVerbose(szFormat
, argptr
);
207 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
208 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
210 if ( IsLoggingEnabled() ) { \
211 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
213 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
215 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
218 void wxLog##level(const wxChar *szFormat, ...) \
221 va_start(argptr, szFormat); \
222 wxVLog##level(szFormat, argptr); \
226 void wxVLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, va_list argptr
)
228 if ( IsLoggingEnabled() && wxLog::IsAllowedTraceMask(mask
) ) {
229 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
232 size_t len
= WXSIZEOF(s_szBuf
);
233 wxStrncpy(s_szBuf
, _T("("), len
);
234 len
-= 1; // strlen("(")
236 wxStrncat(p
, mask
, len
);
237 size_t lenMask
= wxStrlen(mask
);
241 wxStrncat(p
, _T(") "), len
);
245 wxVsnprintf(p
, len
, szFormat
, argptr
);
247 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
251 void wxLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, ...)
254 va_start(argptr
, szFormat
);
255 wxVLogTrace(mask
, szFormat
, argptr
);
259 void wxVLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, va_list argptr
)
261 // we check that all of mask bits are set in the current mask, so
262 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
263 // if both bits are set.
264 if ( IsLoggingEnabled() && ((wxLog::GetTraceMask() & mask
) == mask
) ) {
265 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
267 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
269 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
273 void wxLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, ...)
276 va_start(argptr
, szFormat
);
277 wxVLogTrace(mask
, szFormat
, argptr
);
282 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
285 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
286 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
288 // wxLogSysError: one uses the last error code, for other you must give it
291 // common part of both wxLogSysError
292 void wxLogSysErrorHelper(long lErrCode
)
294 wxChar szErrMsg
[LOG_BUFFER_SIZE
/ 2];
295 wxSnprintf(szErrMsg
, WXSIZEOF(szErrMsg
),
296 _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
297 wxStrncat(s_szBuf
, szErrMsg
, WXSIZEOF(s_szBuf
) - wxStrlen(s_szBuf
));
299 wxLog::OnLog(wxLOG_Error
, s_szBuf
, time(NULL
));
302 void WXDLLEXPORT
wxVLogSysError(const wxChar
*szFormat
, va_list argptr
)
304 if ( IsLoggingEnabled() ) {
305 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
307 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
309 wxLogSysErrorHelper(wxSysErrorCode());
313 void WXDLLEXPORT
wxLogSysError(const wxChar
*szFormat
, ...)
316 va_start(argptr
, szFormat
);
317 wxVLogSysError(szFormat
, argptr
);
321 void WXDLLEXPORT
wxVLogSysError(long lErrCode
, const wxChar
*szFormat
, va_list argptr
)
323 if ( IsLoggingEnabled() ) {
324 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
326 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
328 wxLogSysErrorHelper(lErrCode
);
332 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const wxChar
*szFormat
, ...)
335 va_start(argptr
, szFormat
);
336 wxVLogSysError(lErrCode
, szFormat
, argptr
);
340 // ----------------------------------------------------------------------------
341 // wxLog class implementation
342 // ----------------------------------------------------------------------------
346 m_bHasMessages
= FALSE
;
349 wxLog
*wxLog::GetActiveTarget()
351 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
352 // prevent infinite recursion if someone calls wxLogXXX() from
353 // wxApp::CreateLogTarget()
354 static bool s_bInGetActiveTarget
= FALSE
;
355 if ( !s_bInGetActiveTarget
) {
356 s_bInGetActiveTarget
= TRUE
;
358 // ask the application to create a log target for us
359 if ( wxTheApp
!= NULL
)
360 ms_pLogger
= wxTheApp
->CreateLogTarget();
362 ms_pLogger
= new wxLogStderr
;
364 s_bInGetActiveTarget
= FALSE
;
366 // do nothing if it fails - what can we do?
373 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
375 if ( ms_pLogger
!= NULL
) {
376 // flush the old messages before changing because otherwise they might
377 // get lost later if this target is not restored
381 wxLog
*pOldLogger
= ms_pLogger
;
382 ms_pLogger
= pLogger
;
387 void wxLog::DontCreateOnDemand()
389 ms_bAutoCreate
= FALSE
;
391 // this is usually called at the end of the program and we assume that it
392 // is *always* called at the end - so we free memory here to avoid false
393 // memory leak reports from wxWin memory tracking code
397 void wxLog::RemoveTraceMask(const wxString
& str
)
399 int index
= ms_aTraceMasks
.Index(str
);
400 if ( index
!= wxNOT_FOUND
)
401 ms_aTraceMasks
.Remove((size_t)index
);
404 void wxLog::ClearTraceMasks()
406 ms_aTraceMasks
.Clear();
409 void wxLog::TimeStamp(wxString
*str
)
415 (void)time(&timeNow
);
416 wxStrftime(buf
, WXSIZEOF(buf
), ms_timestamp
, localtime(&timeNow
));
419 *str
<< buf
<< wxT(": ");
423 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
426 case wxLOG_FatalError
:
427 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
428 DoLogString(_("Program aborted."), t
);
434 DoLogString(wxString(_("Error: ")) + szString
, t
);
438 DoLogString(wxString(_("Warning: ")) + szString
, t
);
445 default: // log unknown log levels too
446 DoLogString(szString
, t
);
453 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
463 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
465 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
470 // remember that we don't have any more messages to show
471 m_bHasMessages
= FALSE
;
474 // ----------------------------------------------------------------------------
475 // wxLogStderr class implementation
476 // ----------------------------------------------------------------------------
478 wxLogStderr::wxLogStderr(FILE *fp
)
486 #if defined(__WXMAC__) && !defined(__DARWIN__) && (__MWERKS__ > 0x5300)
488 #if !TARGET_API_MAC_CARBON
489 // MetroNub stuff doesn't seem to work in CodeWarrior 5.3 Carbon builds...
491 #ifndef __MetroNubUtils__
492 #include "MetroNubUtils.h"
511 #if TARGET_API_MAC_CARBON
513 #include <CodeFragments.h>
516 CallUniversalProc(UniversalProcPtr theProcPtr
, ProcInfoType procInfo
, ...);
518 ProcPtr gCallUniversalProc_Proc
= NULL
;
522 static MetroNubUserEntryBlock
* gMetroNubEntry
= NULL
;
524 static long fRunOnce
= false;
526 Boolean
IsCompatibleVersion(short inVersion
);
528 /* ---------------------------------------------------------------------------
530 --------------------------------------------------------------------------- */
532 Boolean
IsCompatibleVersion(short inVersion
)
534 Boolean result
= false;
538 MetroNubUserEntryBlock
* block
= (MetroNubUserEntryBlock
*)result
;
540 result
= (inVersion
<= block
->apiHiVersion
);
546 /* ---------------------------------------------------------------------------
548 --------------------------------------------------------------------------- */
550 Boolean
IsMetroNubInstalled()
557 gMetroNubEntry
= NULL
;
559 if (Gestalt(gestaltSystemVersion
, &value
) == noErr
&& value
< 0x1000)
561 /* look for MetroNub's Gestalt selector */
562 if (Gestalt(kMetroNubUserSignature
, &result
) == noErr
)
565 #if TARGET_API_MAC_CARBON
566 if (gCallUniversalProc_Proc
== NULL
)
568 CFragConnectionID connectionID
;
571 ProcPtr symbolAddress
;
573 CFragSymbolClass symbolClass
;
575 symbolAddress
= NULL
;
576 err
= GetSharedLibrary("\pInterfaceLib", kPowerPCCFragArch
, kFindCFrag
,
577 &connectionID
, &mainAddress
, errorString
);
581 gCallUniversalProc_Proc
= NULL
;
585 err
= FindSymbol(connectionID
, "\pCallUniversalProc",
586 (Ptr
*) &gCallUniversalProc_Proc
, &symbolClass
);
590 gCallUniversalProc_Proc
= NULL
;
597 MetroNubUserEntryBlock
* block
= (MetroNubUserEntryBlock
*)result
;
599 /* make sure the version of the API is compatible */
600 if (block
->apiLowVersion
<= kMetroNubUserAPIVersion
&&
601 kMetroNubUserAPIVersion
<= block
->apiHiVersion
)
602 gMetroNubEntry
= block
; /* success! */
611 #if TARGET_API_MAC_CARBON
612 return (gMetroNubEntry
!= NULL
&& gCallUniversalProc_Proc
!= NULL
);
614 return (gMetroNubEntry
!= NULL
);
618 /* ---------------------------------------------------------------------------
619 IsMWDebuggerRunning [v1 API]
620 --------------------------------------------------------------------------- */
622 Boolean
IsMWDebuggerRunning()
624 if (IsMetroNubInstalled())
625 return CallIsDebuggerRunningProc(gMetroNubEntry
->isDebuggerRunning
);
630 /* ---------------------------------------------------------------------------
631 AmIBeingMWDebugged [v1 API]
632 --------------------------------------------------------------------------- */
634 Boolean
AmIBeingMWDebugged()
636 if (IsMetroNubInstalled())
637 return CallAmIBeingDebuggedProc(gMetroNubEntry
->amIBeingDebugged
);
642 /* ---------------------------------------------------------------------------
643 UserSetWatchPoint [v2 API]
644 --------------------------------------------------------------------------- */
646 OSErr
UserSetWatchPoint (Ptr address
, long length
, WatchPointIDT
* watchPointID
)
648 if (IsMetroNubInstalled() && IsCompatibleVersion(kMetroNubUserAPIVersion
))
649 return CallUserSetWatchPointProc(gMetroNubEntry
->userSetWatchPoint
,
650 address
, length
, watchPointID
);
652 return errProcessIsNotClient
;
655 /* ---------------------------------------------------------------------------
656 ClearWatchPoint [v2 API]
657 --------------------------------------------------------------------------- */
659 OSErr
ClearWatchPoint (WatchPointIDT watchPointID
)
661 if (IsMetroNubInstalled() && IsCompatibleVersion(kMetroNubUserAPIVersion
))
662 return CallClearWatchPointProc(gMetroNubEntry
->clearWatchPoint
,
665 return errProcessIsNotClient
;
672 #endif // !TARGET_API_MAC_CARBON
674 #endif // defined(__WXMAC__) && !defined(__DARWIN__) && (__MWERKS__ > 0x5300)
676 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
682 fputs(str
.mb_str(), m_fp
);
683 fputc(_T('\n'), m_fp
);
686 // under Windows, programs usually don't have stderr at all, so show the
687 // messages also under debugger - unless it's a console program
688 #if defined(__WXMSW__) && wxUSE_GUI && !defined(__WXMICROWIN__)
690 OutputDebugString(str
.c_str());
692 #if defined(__WXMAC__) && !defined(__DARWIN__) && wxUSE_GUI
694 strcpy( (char*) pstr
, str
.c_str() ) ;
695 strcat( (char*) pstr
, ";g" ) ;
696 c2pstr( (char*) pstr
) ;
698 Boolean running
= false ;
700 #if !TARGET_API_MAC_CARBON && (__MWERKS__ > 0x5300)
702 if ( IsMWDebuggerRunning() && AmIBeingMWDebugged() )
720 // ----------------------------------------------------------------------------
721 // wxLogStream implementation
722 // ----------------------------------------------------------------------------
724 #if wxUSE_STD_IOSTREAM
725 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
728 m_ostr
= &wxSTD cerr
;
733 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
737 (*m_ostr
) << str
<< wxConvertWX2MB(szString
) << wxSTD endl
;
739 #endif // wxUSE_STD_IOSTREAM
741 // ----------------------------------------------------------------------------
743 // ----------------------------------------------------------------------------
745 wxLogChain::wxLogChain(wxLog
*logger
)
748 m_logOld
= wxLog::SetActiveTarget(this);
751 void wxLogChain::SetLog(wxLog
*logger
)
753 if ( m_logNew
!= this )
756 wxLog::SetActiveTarget(logger
);
761 void wxLogChain::Flush()
766 // be careful to avoid inifinite recursion
767 if ( m_logNew
&& m_logNew
!= this )
771 void wxLogChain::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
773 // let the previous logger show it
774 if ( m_logOld
&& IsPassingMessages() )
776 // bogus cast just to access protected DoLog
777 ((wxLogChain
*)m_logOld
)->DoLog(level
, szString
, t
);
780 if ( m_logNew
&& m_logNew
!= this )
783 ((wxLogChain
*)m_logNew
)->DoLog(level
, szString
, t
);
787 // ----------------------------------------------------------------------------
789 // ----------------------------------------------------------------------------
792 // "'this' : used in base member initializer list" - so what?
793 #pragma warning(disable:4355)
796 wxLogPassThrough::wxLogPassThrough()
802 #pragma warning(default:4355)
805 // ============================================================================
806 // Global functions/variables
807 // ============================================================================
809 // ----------------------------------------------------------------------------
811 // ----------------------------------------------------------------------------
813 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
814 bool wxLog::ms_doLog
= TRUE
;
815 bool wxLog::ms_bAutoCreate
= TRUE
;
816 bool wxLog::ms_bVerbose
= FALSE
;
818 size_t wxLog::ms_suspendCount
= 0;
821 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
823 const wxChar
*wxLog::ms_timestamp
= NULL
; // save space
826 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
827 wxArrayString
wxLog::ms_aTraceMasks
;
829 // ----------------------------------------------------------------------------
830 // stdout error logging helper
831 // ----------------------------------------------------------------------------
833 // helper function: wraps the message and justifies it under given position
834 // (looks more pretty on the terminal). Also adds newline at the end.
836 // TODO this is now disabled until I find a portable way of determining the
837 // terminal window size (ok, I found it but does anybody really cares?)
838 #ifdef LOG_PRETTY_WRAP
839 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
841 size_t nMax
= 80; // FIXME
842 size_t nStart
= strlen(pszPrefix
);
846 while ( *psz
!= '\0' ) {
847 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
851 if ( *psz
!= '\0' ) {
853 for ( n
= 0; n
< nStart
; n
++ )
856 // as we wrapped, squeeze all white space
857 while ( isspace(*psz
) )
864 #endif //LOG_PRETTY_WRAP
866 // ----------------------------------------------------------------------------
867 // error code/error message retrieval functions
868 // ----------------------------------------------------------------------------
870 // get error code from syste
871 unsigned long wxSysErrorCode()
873 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
875 return ::GetLastError();
877 // TODO what to do on Windows 3.1?
885 // get error message from system
886 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
889 nErrCode
= wxSysErrorCode();
891 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
893 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
895 // get error message from system
897 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
899 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
903 // copy it to our buffer and free memory
904 if( lpMsgBuf
!= 0 ) {
905 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
906 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
910 // returned string is capitalized and ended with '\r\n' - bad
911 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
912 size_t len
= wxStrlen(s_szBuf
);
915 if ( s_szBuf
[len
- 2] == wxT('\r') )
916 s_szBuf
[len
- 2] = wxT('\0');
920 s_szBuf
[0] = wxT('\0');
930 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
931 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
934 return strerror((int)nErrCode
);