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"
40 #include "wx/msw/private.h"
46 #include "wx/textfile.h"
48 #include "wx/wxchar.h"
50 #include "wx/thread.h"
54 // other standard headers
59 #if defined(__WXMSW__)
60 #include "wx/msw/private.h" // includes windows.h for OutputDebugString
63 #if defined(__WXMAC__)
64 #include "wx/mac/private.h" // includes mac headers
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_szBuf
[LOG_BUFFER_SIZE
];
95 // the critical section protecting the static buffer
96 static wxCriticalSection gs_csLogBuf
;
98 #endif // wxUSE_THREADS
100 // return true if we have a non NULL non disabled log target
101 static inline bool IsLoggingEnabled()
103 return wxLog::IsEnabled() && (wxLog::GetActiveTarget() != NULL
);
106 // ----------------------------------------------------------------------------
107 // implementation of Log functions
109 // NB: unfortunately we need all these distinct functions, we can't make them
110 // macros and not all compilers inline vararg functions.
111 // ----------------------------------------------------------------------------
113 // generic log function
114 void wxLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, ...)
116 if ( IsLoggingEnabled() ) {
117 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
120 va_start(argptr
, szFormat
);
121 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
124 wxLog::OnLog(level
, s_szBuf
, time(NULL
));
128 #define IMPLEMENT_LOG_FUNCTION(level) \
129 void wxLog##level(const wxChar *szFormat, ...) \
131 if ( IsLoggingEnabled() ) { \
132 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
135 va_start(argptr, szFormat); \
136 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
139 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
143 IMPLEMENT_LOG_FUNCTION(FatalError
)
144 IMPLEMENT_LOG_FUNCTION(Error
)
145 IMPLEMENT_LOG_FUNCTION(Warning
)
146 IMPLEMENT_LOG_FUNCTION(Message
)
147 IMPLEMENT_LOG_FUNCTION(Info
)
148 IMPLEMENT_LOG_FUNCTION(Status
)
150 // same as info, but only if 'verbose' mode is on
151 void wxLogVerbose(const wxChar
*szFormat
, ...)
153 if ( IsLoggingEnabled() ) {
154 wxLog
*pLog
= wxLog::GetActiveTarget();
155 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
156 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
159 va_start(argptr
, szFormat
);
160 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
163 wxLog::OnLog(wxLOG_Info
, s_szBuf
, time(NULL
));
170 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
171 void wxLog##level(const wxChar *szFormat, ...) \
173 if ( IsLoggingEnabled() ) { \
174 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
177 va_start(argptr, szFormat); \
178 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
181 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
185 void wxLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, ...)
187 if ( IsLoggingEnabled() && wxLog::IsAllowedTraceMask(mask
) ) {
188 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
191 size_t len
= WXSIZEOF(s_szBuf
);
192 wxStrncpy(s_szBuf
, _T("("), len
);
193 len
-= 1; // strlen("(")
195 wxStrncat(p
, mask
, len
);
196 size_t lenMask
= wxStrlen(mask
);
200 wxStrncat(p
, _T(") "), len
);
205 va_start(argptr
, szFormat
);
206 wxVsnprintf(p
, len
, szFormat
, argptr
);
209 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
213 void wxLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, ...)
215 // we check that all of mask bits are set in the current mask, so
216 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
217 // if both bits are set.
218 if ( IsLoggingEnabled() && ((wxLog::GetTraceMask() & mask
) == mask
) ) {
219 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
222 va_start(argptr
, szFormat
);
223 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
226 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
231 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
234 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
235 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
237 // wxLogSysError: one uses the last error code, for other you must give it
240 // common part of both wxLogSysError
241 void wxLogSysErrorHelper(long lErrCode
)
243 wxChar szErrMsg
[LOG_BUFFER_SIZE
/ 2];
244 wxSnprintf(szErrMsg
, WXSIZEOF(szErrMsg
),
245 _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
246 wxStrncat(s_szBuf
, szErrMsg
, WXSIZEOF(s_szBuf
) - wxStrlen(s_szBuf
));
248 wxLog::OnLog(wxLOG_Error
, s_szBuf
, time(NULL
));
251 void WXDLLEXPORT
wxLogSysError(const wxChar
*szFormat
, ...)
253 if ( IsLoggingEnabled() ) {
254 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
257 va_start(argptr
, szFormat
);
258 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
261 wxLogSysErrorHelper(wxSysErrorCode());
265 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const wxChar
*szFormat
, ...)
267 if ( IsLoggingEnabled() ) {
268 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
271 va_start(argptr
, szFormat
);
272 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
275 wxLogSysErrorHelper(lErrCode
);
279 // ----------------------------------------------------------------------------
280 // wxLog class implementation
281 // ----------------------------------------------------------------------------
285 m_bHasMessages
= FALSE
;
288 wxLog
*wxLog::GetActiveTarget()
290 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
291 // prevent infinite recursion if someone calls wxLogXXX() from
292 // wxApp::CreateLogTarget()
293 static bool s_bInGetActiveTarget
= FALSE
;
294 if ( !s_bInGetActiveTarget
) {
295 s_bInGetActiveTarget
= TRUE
;
297 // ask the application to create a log target for us
298 if ( wxTheApp
!= NULL
)
299 ms_pLogger
= wxTheApp
->CreateLogTarget();
301 ms_pLogger
= new wxLogStderr
;
303 s_bInGetActiveTarget
= FALSE
;
305 // do nothing if it fails - what can we do?
312 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
314 if ( ms_pLogger
!= NULL
) {
315 // flush the old messages before changing because otherwise they might
316 // get lost later if this target is not restored
320 wxLog
*pOldLogger
= ms_pLogger
;
321 ms_pLogger
= pLogger
;
326 void wxLog::DontCreateOnDemand()
328 ms_bAutoCreate
= FALSE
;
330 // this is usually called at the end of the program and we assume that it
331 // is *always* called at the end - so we free memory here to avoid false
332 // memory leak reports from wxWin memory tracking code
336 void wxLog::RemoveTraceMask(const wxString
& str
)
338 int index
= ms_aTraceMasks
.Index(str
);
339 if ( index
!= wxNOT_FOUND
)
340 ms_aTraceMasks
.Remove((size_t)index
);
343 void wxLog::ClearTraceMasks()
345 ms_aTraceMasks
.Clear();
348 void wxLog::TimeStamp(wxString
*str
)
354 (void)time(&timeNow
);
355 wxStrftime(buf
, WXSIZEOF(buf
), ms_timestamp
, localtime(&timeNow
));
358 *str
<< buf
<< wxT(": ");
362 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
365 case wxLOG_FatalError
:
366 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
367 DoLogString(_("Program aborted."), t
);
373 DoLogString(wxString(_("Error: ")) + szString
, t
);
377 DoLogString(wxString(_("Warning: ")) + szString
, t
);
384 default: // log unknown log levels too
385 DoLogString(szString
, t
);
392 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
402 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
404 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
409 // remember that we don't have any more messages to show
410 m_bHasMessages
= FALSE
;
413 // ----------------------------------------------------------------------------
414 // wxLogStderr class implementation
415 // ----------------------------------------------------------------------------
417 wxLogStderr::wxLogStderr(FILE *fp
)
425 #if defined(__WXMAC__) && !defined(__DARWIN__) && (__MWERKS__ > 0x5300)
427 #if !TARGET_API_MAC_CARBON
428 // MetroNub stuff doesn't seem to work in CodeWarrior 5.3 Carbon builds...
430 #ifndef __MetroNubUtils__
431 #include "MetroNubUtils.h"
450 #if TARGET_API_MAC_CARBON
452 #include <CodeFragments.h>
455 CallUniversalProc(UniversalProcPtr theProcPtr
, ProcInfoType procInfo
, ...);
457 ProcPtr gCallUniversalProc_Proc
= NULL
;
461 static MetroNubUserEntryBlock
* gMetroNubEntry
= NULL
;
463 static long fRunOnce
= false;
465 Boolean
IsCompatibleVersion(short inVersion
);
467 /* ---------------------------------------------------------------------------
469 --------------------------------------------------------------------------- */
471 Boolean
IsCompatibleVersion(short inVersion
)
473 Boolean result
= false;
477 MetroNubUserEntryBlock
* block
= (MetroNubUserEntryBlock
*)result
;
479 result
= (inVersion
<= block
->apiHiVersion
);
485 /* ---------------------------------------------------------------------------
487 --------------------------------------------------------------------------- */
489 Boolean
IsMetroNubInstalled()
496 gMetroNubEntry
= NULL
;
498 if (Gestalt(gestaltSystemVersion
, &value
) == noErr
&& value
< 0x1000)
500 /* look for MetroNub's Gestalt selector */
501 if (Gestalt(kMetroNubUserSignature
, &result
) == noErr
)
504 #if TARGET_API_MAC_CARBON
505 if (gCallUniversalProc_Proc
== NULL
)
507 CFragConnectionID connectionID
;
510 ProcPtr symbolAddress
;
512 CFragSymbolClass symbolClass
;
514 symbolAddress
= NULL
;
515 err
= GetSharedLibrary("\pInterfaceLib", kPowerPCCFragArch
, kFindCFrag
,
516 &connectionID
, &mainAddress
, errorString
);
520 gCallUniversalProc_Proc
= NULL
;
524 err
= FindSymbol(connectionID
, "\pCallUniversalProc",
525 (Ptr
*) &gCallUniversalProc_Proc
, &symbolClass
);
529 gCallUniversalProc_Proc
= NULL
;
536 MetroNubUserEntryBlock
* block
= (MetroNubUserEntryBlock
*)result
;
538 /* make sure the version of the API is compatible */
539 if (block
->apiLowVersion
<= kMetroNubUserAPIVersion
&&
540 kMetroNubUserAPIVersion
<= block
->apiHiVersion
)
541 gMetroNubEntry
= block
; /* success! */
550 #if TARGET_API_MAC_CARBON
551 return (gMetroNubEntry
!= NULL
&& gCallUniversalProc_Proc
!= NULL
);
553 return (gMetroNubEntry
!= NULL
);
557 /* ---------------------------------------------------------------------------
558 IsMWDebuggerRunning [v1 API]
559 --------------------------------------------------------------------------- */
561 Boolean
IsMWDebuggerRunning()
563 if (IsMetroNubInstalled())
564 return CallIsDebuggerRunningProc(gMetroNubEntry
->isDebuggerRunning
);
569 /* ---------------------------------------------------------------------------
570 AmIBeingMWDebugged [v1 API]
571 --------------------------------------------------------------------------- */
573 Boolean
AmIBeingMWDebugged()
575 if (IsMetroNubInstalled())
576 return CallAmIBeingDebuggedProc(gMetroNubEntry
->amIBeingDebugged
);
581 /* ---------------------------------------------------------------------------
582 UserSetWatchPoint [v2 API]
583 --------------------------------------------------------------------------- */
585 OSErr
UserSetWatchPoint (Ptr address
, long length
, WatchPointIDT
* watchPointID
)
587 if (IsMetroNubInstalled() && IsCompatibleVersion(kMetroNubUserAPIVersion
))
588 return CallUserSetWatchPointProc(gMetroNubEntry
->userSetWatchPoint
,
589 address
, length
, watchPointID
);
591 return errProcessIsNotClient
;
594 /* ---------------------------------------------------------------------------
595 ClearWatchPoint [v2 API]
596 --------------------------------------------------------------------------- */
598 OSErr
ClearWatchPoint (WatchPointIDT watchPointID
)
600 if (IsMetroNubInstalled() && IsCompatibleVersion(kMetroNubUserAPIVersion
))
601 return CallClearWatchPointProc(gMetroNubEntry
->clearWatchPoint
,
604 return errProcessIsNotClient
;
611 #endif // !TARGET_API_MAC_CARBON
613 #endif // defined(__WXMAC__) && !defined(__DARWIN__) && (__MWERKS__ > 0x5300)
615 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
621 fputs(str
.mb_str(), m_fp
);
622 fputc(_T('\n'), m_fp
);
625 // under Windows, programs usually don't have stderr at all, so show the
626 // messages also under debugger - unless it's a console program
627 #if defined(__WXMSW__) && wxUSE_GUI && !defined(__WXMICROWIN__)
629 OutputDebugString(str
.c_str());
631 #if defined(__WXMAC__) && !defined(__DARWIN__) && wxUSE_GUI
633 strcpy( (char*) pstr
, str
.c_str() ) ;
634 strcat( (char*) pstr
, ";g" ) ;
635 c2pstr( (char*) pstr
) ;
637 Boolean running
= false ;
639 #if !TARGET_API_MAC_CARBON && (__MWERKS__ > 0x5300)
641 if ( IsMWDebuggerRunning() && AmIBeingMWDebugged() )
659 // ----------------------------------------------------------------------------
660 // wxLogStream implementation
661 // ----------------------------------------------------------------------------
663 #if wxUSE_STD_IOSTREAM
664 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
667 m_ostr
= &wxSTD cerr
;
672 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
676 (*m_ostr
) << str
<< wxConvertWX2MB(szString
) << wxSTD endl
;
678 #endif // wxUSE_STD_IOSTREAM
680 // ----------------------------------------------------------------------------
682 // ----------------------------------------------------------------------------
684 wxLogChain::wxLogChain(wxLog
*logger
)
687 m_logOld
= wxLog::SetActiveTarget(this);
690 void wxLogChain::SetLog(wxLog
*logger
)
692 if ( m_logNew
!= this )
695 wxLog::SetActiveTarget(logger
);
700 void wxLogChain::Flush()
705 // be careful to avoid inifinite recursion
706 if ( m_logNew
&& m_logNew
!= this )
710 void wxLogChain::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
712 // let the previous logger show it
713 if ( m_logOld
&& IsPassingMessages() )
715 // bogus cast just to access protected DoLog
716 ((wxLogChain
*)m_logOld
)->DoLog(level
, szString
, t
);
719 if ( m_logNew
&& m_logNew
!= this )
722 ((wxLogChain
*)m_logNew
)->DoLog(level
, szString
, t
);
726 // ----------------------------------------------------------------------------
728 // ----------------------------------------------------------------------------
731 // "'this' : used in base member initializer list" - so what?
732 #pragma warning(disable:4355)
735 wxLogPassThrough::wxLogPassThrough()
741 #pragma warning(default:4355)
744 // ============================================================================
745 // Global functions/variables
746 // ============================================================================
748 // ----------------------------------------------------------------------------
750 // ----------------------------------------------------------------------------
752 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
753 bool wxLog::ms_doLog
= TRUE
;
754 bool wxLog::ms_bAutoCreate
= TRUE
;
755 bool wxLog::ms_bVerbose
= FALSE
;
757 size_t wxLog::ms_suspendCount
= 0;
760 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
762 const wxChar
*wxLog::ms_timestamp
= NULL
; // save space
765 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
766 wxArrayString
wxLog::ms_aTraceMasks
;
768 // ----------------------------------------------------------------------------
769 // stdout error logging helper
770 // ----------------------------------------------------------------------------
772 // helper function: wraps the message and justifies it under given position
773 // (looks more pretty on the terminal). Also adds newline at the end.
775 // TODO this is now disabled until I find a portable way of determining the
776 // terminal window size (ok, I found it but does anybody really cares?)
777 #ifdef LOG_PRETTY_WRAP
778 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
780 size_t nMax
= 80; // FIXME
781 size_t nStart
= strlen(pszPrefix
);
785 while ( *psz
!= '\0' ) {
786 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
790 if ( *psz
!= '\0' ) {
792 for ( n
= 0; n
< nStart
; n
++ )
795 // as we wrapped, squeeze all white space
796 while ( isspace(*psz
) )
803 #endif //LOG_PRETTY_WRAP
805 // ----------------------------------------------------------------------------
806 // error code/error message retrieval functions
807 // ----------------------------------------------------------------------------
809 // get error code from syste
810 unsigned long wxSysErrorCode()
812 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
814 return ::GetLastError();
816 // TODO what to do on Windows 3.1?
824 // get error message from system
825 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
828 nErrCode
= wxSysErrorCode();
830 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
832 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
834 // get error message from system
836 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
838 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
842 // copy it to our buffer and free memory
843 if( lpMsgBuf
!= 0 ) {
844 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
845 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
849 // returned string is capitalized and ended with '\r\n' - bad
850 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
851 size_t len
= wxStrlen(s_szBuf
);
854 if ( s_szBuf
[len
- 2] == wxT('\r') )
855 s_szBuf
[len
- 2] = wxT('\0');
859 s_szBuf
[0] = wxT('\0');
869 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
870 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
873 return strerror((int)nErrCode
);