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__)
427 #ifndef __MetroNubUtils__
428 #include "MetroNubUtils.h"
447 #if TARGET_API_MAC_CARBON
449 #include <CodeFragments.h>
452 CallUniversalProc(UniversalProcPtr theProcPtr
, ProcInfoType procInfo
, ...);
454 ProcPtr gCallUniversalProc_Proc
= NULL
;
458 static MetroNubUserEntryBlock
* gMetroNubEntry
= NULL
;
460 static long fRunOnce
= false;
462 Boolean
IsCompatibleVersion(short inVersion
);
464 /* ---------------------------------------------------------------------------
466 --------------------------------------------------------------------------- */
468 Boolean
IsCompatibleVersion(short inVersion
)
470 Boolean result
= false;
474 MetroNubUserEntryBlock
* block
= (MetroNubUserEntryBlock
*)result
;
476 result
= (inVersion
<= block
->apiHiVersion
);
482 /* ---------------------------------------------------------------------------
484 --------------------------------------------------------------------------- */
486 Boolean
IsMetroNubInstalled()
493 gMetroNubEntry
= NULL
;
495 if (Gestalt(gestaltSystemVersion
, &value
) == noErr
&& value
< 0x1000)
497 /* look for MetroNub's Gestalt selector */
498 if (Gestalt(kMetroNubUserSignature
, &result
) == noErr
)
501 #if TARGET_API_MAC_CARBON
502 if (gCallUniversalProc_Proc
== NULL
)
504 CFragConnectionID connectionID
;
507 ProcPtr symbolAddress
;
509 CFragSymbolClass symbolClass
;
511 symbolAddress
= NULL
;
512 err
= GetSharedLibrary("\pInterfaceLib", kPowerPCCFragArch
, kFindCFrag
,
513 &connectionID
, &mainAddress
, errorString
);
517 gCallUniversalProc_Proc
= NULL
;
521 err
= FindSymbol(connectionID
, "\pCallUniversalProc",
522 (Ptr
*) &gCallUniversalProc_Proc
, &symbolClass
);
526 gCallUniversalProc_Proc
= NULL
;
533 MetroNubUserEntryBlock
* block
= (MetroNubUserEntryBlock
*)result
;
535 /* make sure the version of the API is compatible */
536 if (block
->apiLowVersion
<= kMetroNubUserAPIVersion
&&
537 kMetroNubUserAPIVersion
<= block
->apiHiVersion
)
538 gMetroNubEntry
= block
; /* success! */
547 #if TARGET_API_MAC_CARBON
548 return (gMetroNubEntry
!= NULL
&& gCallUniversalProc_Proc
!= NULL
);
550 return (gMetroNubEntry
!= NULL
);
554 /* ---------------------------------------------------------------------------
555 IsMWDebuggerRunning [v1 API]
556 --------------------------------------------------------------------------- */
558 Boolean
IsMWDebuggerRunning()
560 if (IsMetroNubInstalled())
561 return CallIsDebuggerRunningProc(gMetroNubEntry
->isDebuggerRunning
);
566 /* ---------------------------------------------------------------------------
567 AmIBeingMWDebugged [v1 API]
568 --------------------------------------------------------------------------- */
570 Boolean
AmIBeingMWDebugged()
572 if (IsMetroNubInstalled())
573 return CallAmIBeingDebuggedProc(gMetroNubEntry
->amIBeingDebugged
);
578 /* ---------------------------------------------------------------------------
579 UserSetWatchPoint [v2 API]
580 --------------------------------------------------------------------------- */
582 OSErr
UserSetWatchPoint (Ptr address
, long length
, WatchPointIDT
* watchPointID
)
584 if (IsMetroNubInstalled() && IsCompatibleVersion(kMetroNubUserAPIVersion
))
585 return CallUserSetWatchPointProc(gMetroNubEntry
->userSetWatchPoint
,
586 address
, length
, watchPointID
);
588 return errProcessIsNotClient
;
591 /* ---------------------------------------------------------------------------
592 ClearWatchPoint [v2 API]
593 --------------------------------------------------------------------------- */
595 OSErr
ClearWatchPoint (WatchPointIDT watchPointID
)
597 if (IsMetroNubInstalled() && IsCompatibleVersion(kMetroNubUserAPIVersion
))
598 return CallClearWatchPointProc(gMetroNubEntry
->clearWatchPoint
,
601 return errProcessIsNotClient
;
610 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
616 fputs(str
.mb_str(), m_fp
);
617 fputc(_T('\n'), m_fp
);
620 // under Windows, programs usually don't have stderr at all, so show the
621 // messages also under debugger - unless it's a console program
622 #if defined(__WXMSW__) && wxUSE_GUI && !defined(__WXMICROWIN__)
624 OutputDebugString(str
.c_str());
626 #if defined(__WXMAC__) && !defined(__DARWIN__) && wxUSE_GUI
628 strcpy( (char*) pstr
, str
.c_str() ) ;
629 strcat( (char*) pstr
, ";g" ) ;
630 c2pstr( (char*) pstr
) ;
632 Boolean running
= false ;
634 if ( IsMWDebuggerRunning() && AmIBeingMWDebugged() )
650 // ----------------------------------------------------------------------------
651 // wxLogStream implementation
652 // ----------------------------------------------------------------------------
654 #if wxUSE_STD_IOSTREAM
655 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
658 m_ostr
= &wxSTD cerr
;
663 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
667 (*m_ostr
) << str
<< wxConvertWX2MB(szString
) << wxSTD endl
;
669 #endif // wxUSE_STD_IOSTREAM
671 // ----------------------------------------------------------------------------
673 // ----------------------------------------------------------------------------
675 wxLogChain::wxLogChain(wxLog
*logger
)
678 m_logOld
= wxLog::SetActiveTarget(this);
681 void wxLogChain::SetLog(wxLog
*logger
)
683 if ( m_logNew
!= this )
686 wxLog::SetActiveTarget(logger
);
691 void wxLogChain::Flush()
696 // be careful to avoid inifinite recursion
697 if ( m_logNew
&& m_logNew
!= this )
701 void wxLogChain::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
703 // let the previous logger show it
704 if ( m_logOld
&& IsPassingMessages() )
706 // bogus cast just to access protected DoLog
707 ((wxLogChain
*)m_logOld
)->DoLog(level
, szString
, t
);
710 if ( m_logNew
&& m_logNew
!= this )
713 ((wxLogChain
*)m_logNew
)->DoLog(level
, szString
, t
);
717 // ----------------------------------------------------------------------------
719 // ----------------------------------------------------------------------------
722 // "'this' : used in base member initializer list" - so what?
723 #pragma warning(disable:4355)
726 wxLogPassThrough::wxLogPassThrough()
732 #pragma warning(default:4355)
735 // ============================================================================
736 // Global functions/variables
737 // ============================================================================
739 // ----------------------------------------------------------------------------
741 // ----------------------------------------------------------------------------
743 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
744 bool wxLog::ms_doLog
= TRUE
;
745 bool wxLog::ms_bAutoCreate
= TRUE
;
746 bool wxLog::ms_bVerbose
= FALSE
;
748 size_t wxLog::ms_suspendCount
= 0;
751 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
753 const wxChar
*wxLog::ms_timestamp
= NULL
; // save space
756 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
757 wxArrayString
wxLog::ms_aTraceMasks
;
759 // ----------------------------------------------------------------------------
760 // stdout error logging helper
761 // ----------------------------------------------------------------------------
763 // helper function: wraps the message and justifies it under given position
764 // (looks more pretty on the terminal). Also adds newline at the end.
766 // TODO this is now disabled until I find a portable way of determining the
767 // terminal window size (ok, I found it but does anybody really cares?)
768 #ifdef LOG_PRETTY_WRAP
769 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
771 size_t nMax
= 80; // FIXME
772 size_t nStart
= strlen(pszPrefix
);
776 while ( *psz
!= '\0' ) {
777 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
781 if ( *psz
!= '\0' ) {
783 for ( n
= 0; n
< nStart
; n
++ )
786 // as we wrapped, squeeze all white space
787 while ( isspace(*psz
) )
794 #endif //LOG_PRETTY_WRAP
796 // ----------------------------------------------------------------------------
797 // error code/error message retrieval functions
798 // ----------------------------------------------------------------------------
800 // get error code from syste
801 unsigned long wxSysErrorCode()
803 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
805 return ::GetLastError();
807 // TODO what to do on Windows 3.1?
815 // get error message from system
816 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
819 nErrCode
= wxSysErrorCode();
821 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
823 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
825 // get error message from system
827 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
829 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
833 // copy it to our buffer and free memory
834 if( lpMsgBuf
!= 0 ) {
835 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
836 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
840 // returned string is capitalized and ended with '\r\n' - bad
841 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
842 size_t len
= wxStrlen(s_szBuf
);
845 if ( s_szBuf
[len
- 2] == wxT('\r') )
846 s_szBuf
[len
- 2] = wxT('\0');
850 s_szBuf
[0] = wxT('\0');
860 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
861 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
864 return strerror((int)nErrCode
);