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 // ----------------------------------------------------------------------------
64 // non member functions
65 // ----------------------------------------------------------------------------
67 // define this to enable wrapping of log messages
68 //#define LOG_PRETTY_WRAP
70 #ifdef LOG_PRETTY_WRAP
71 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
74 // ============================================================================
76 // ============================================================================
78 // ----------------------------------------------------------------------------
80 // ----------------------------------------------------------------------------
82 // log functions can't allocate memory (LogError("out of memory...") should
83 // work!), so we use a static buffer for all log messages
84 #define LOG_BUFFER_SIZE (4096)
86 // static buffer for error messages
87 static wxChar s_szBuf
[LOG_BUFFER_SIZE
];
91 // the critical section protecting the static buffer
92 static wxCriticalSection gs_csLogBuf
;
94 #endif // wxUSE_THREADS
96 // return true if we have a non NULL non disabled log target
97 static inline bool IsLoggingEnabled()
99 return wxLog::IsEnabled() && (wxLog::GetActiveTarget() != NULL
);
102 // ----------------------------------------------------------------------------
103 // implementation of Log functions
105 // NB: unfortunately we need all these distinct functions, we can't make them
106 // macros and not all compilers inline vararg functions.
107 // ----------------------------------------------------------------------------
109 // generic log function
110 void wxLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, ...)
112 if ( IsLoggingEnabled() ) {
113 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
116 va_start(argptr
, szFormat
);
117 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
120 wxLog::OnLog(level
, s_szBuf
, time(NULL
));
124 #define IMPLEMENT_LOG_FUNCTION(level) \
125 void wxLog##level(const wxChar *szFormat, ...) \
127 if ( IsLoggingEnabled() ) { \
128 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
131 va_start(argptr, szFormat); \
132 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
135 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
139 IMPLEMENT_LOG_FUNCTION(FatalError
)
140 IMPLEMENT_LOG_FUNCTION(Error
)
141 IMPLEMENT_LOG_FUNCTION(Warning
)
142 IMPLEMENT_LOG_FUNCTION(Message
)
143 IMPLEMENT_LOG_FUNCTION(Info
)
144 IMPLEMENT_LOG_FUNCTION(Status
)
146 // same as info, but only if 'verbose' mode is on
147 void wxLogVerbose(const wxChar
*szFormat
, ...)
149 if ( IsLoggingEnabled() ) {
150 wxLog
*pLog
= wxLog::GetActiveTarget();
151 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
152 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
155 va_start(argptr
, szFormat
);
156 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
159 wxLog::OnLog(wxLOG_Info
, s_szBuf
, time(NULL
));
166 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
167 void wxLog##level(const wxChar *szFormat, ...) \
169 if ( IsLoggingEnabled() ) { \
170 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
173 va_start(argptr, szFormat); \
174 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
177 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
181 void wxLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, ...)
183 if ( IsLoggingEnabled() && wxLog::IsAllowedTraceMask(mask
) ) {
184 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
187 size_t len
= WXSIZEOF(s_szBuf
);
188 wxStrncpy(s_szBuf
, _T("("), len
);
189 len
-= 1; // strlen("(")
191 wxStrncat(p
, mask
, len
);
192 size_t lenMask
= wxStrlen(mask
);
196 wxStrncat(p
, _T(") "), len
);
201 va_start(argptr
, szFormat
);
202 wxVsnprintf(p
, len
, szFormat
, argptr
);
205 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
209 void wxLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, ...)
211 // we check that all of mask bits are set in the current mask, so
212 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
213 // if both bits are set.
214 if ( IsLoggingEnabled() && ((wxLog::GetTraceMask() & mask
) == mask
) ) {
215 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
218 va_start(argptr
, szFormat
);
219 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
222 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
227 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
230 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
231 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
233 // wxLogSysError: one uses the last error code, for other you must give it
236 // common part of both wxLogSysError
237 void wxLogSysErrorHelper(long lErrCode
)
239 wxChar szErrMsg
[LOG_BUFFER_SIZE
/ 2];
240 wxSnprintf(szErrMsg
, WXSIZEOF(szErrMsg
),
241 _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
242 wxStrncat(s_szBuf
, szErrMsg
, WXSIZEOF(s_szBuf
) - wxStrlen(s_szBuf
));
244 wxLog::OnLog(wxLOG_Error
, s_szBuf
, time(NULL
));
247 void WXDLLEXPORT
wxLogSysError(const wxChar
*szFormat
, ...)
249 if ( IsLoggingEnabled() ) {
250 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
253 va_start(argptr
, szFormat
);
254 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
257 wxLogSysErrorHelper(wxSysErrorCode());
261 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const wxChar
*szFormat
, ...)
263 if ( IsLoggingEnabled() ) {
264 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
267 va_start(argptr
, szFormat
);
268 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
271 wxLogSysErrorHelper(lErrCode
);
275 // ----------------------------------------------------------------------------
276 // wxLog class implementation
277 // ----------------------------------------------------------------------------
281 m_bHasMessages
= FALSE
;
284 wxLog
*wxLog::GetActiveTarget()
286 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
287 // prevent infinite recursion if someone calls wxLogXXX() from
288 // wxApp::CreateLogTarget()
289 static bool s_bInGetActiveTarget
= FALSE
;
290 if ( !s_bInGetActiveTarget
) {
291 s_bInGetActiveTarget
= TRUE
;
293 // ask the application to create a log target for us
294 if ( wxTheApp
!= NULL
)
295 ms_pLogger
= wxTheApp
->CreateLogTarget();
297 ms_pLogger
= new wxLogStderr
;
299 s_bInGetActiveTarget
= FALSE
;
301 // do nothing if it fails - what can we do?
308 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
310 if ( ms_pLogger
!= NULL
) {
311 // flush the old messages before changing because otherwise they might
312 // get lost later if this target is not restored
316 wxLog
*pOldLogger
= ms_pLogger
;
317 ms_pLogger
= pLogger
;
322 void wxLog::DontCreateOnDemand()
324 ms_bAutoCreate
= FALSE
;
326 // this is usually called at the end of the program and we assume that it
327 // is *always* called at the end - so we free memory here to avoid false
328 // memory leak reports from wxWin memory tracking code
332 void wxLog::RemoveTraceMask(const wxString
& str
)
334 int index
= ms_aTraceMasks
.Index(str
);
335 if ( index
!= wxNOT_FOUND
)
336 ms_aTraceMasks
.Remove((size_t)index
);
339 void wxLog::ClearTraceMasks()
341 ms_aTraceMasks
.Clear();
344 void wxLog::TimeStamp(wxString
*str
)
350 (void)time(&timeNow
);
351 wxStrftime(buf
, WXSIZEOF(buf
), ms_timestamp
, localtime(&timeNow
));
354 *str
<< buf
<< wxT(": ");
358 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
361 case wxLOG_FatalError
:
362 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
363 DoLogString(_("Program aborted."), t
);
369 DoLogString(wxString(_("Error: ")) + szString
, t
);
373 DoLogString(wxString(_("Warning: ")) + szString
, t
);
380 default: // log unknown log levels too
381 DoLogString(szString
, t
);
388 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
398 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
400 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
405 // remember that we don't have any more messages to show
406 m_bHasMessages
= FALSE
;
409 // ----------------------------------------------------------------------------
410 // wxLogStderr class implementation
411 // ----------------------------------------------------------------------------
413 wxLogStderr::wxLogStderr(FILE *fp
)
421 #if defined(__WXMAC__) && !defined(__DARWIN__)
423 #ifndef __MetroNubUtils__
424 #include "MetroNubUtils.h"
443 #if TARGET_API_MAC_CARBON
445 #include <CodeFragments.h>
448 CallUniversalProc(UniversalProcPtr theProcPtr
, ProcInfoType procInfo
, ...);
450 ProcPtr gCallUniversalProc_Proc
= NULL
;
454 static MetroNubUserEntryBlock
* gMetroNubEntry
= NULL
;
456 static long fRunOnce
= false;
458 Boolean
IsCompatibleVersion(short inVersion
);
460 /* ---------------------------------------------------------------------------
462 --------------------------------------------------------------------------- */
464 Boolean
IsCompatibleVersion(short inVersion
)
466 Boolean result
= false;
470 MetroNubUserEntryBlock
* block
= (MetroNubUserEntryBlock
*)result
;
472 result
= (inVersion
<= block
->apiHiVersion
);
478 /* ---------------------------------------------------------------------------
480 --------------------------------------------------------------------------- */
482 Boolean
IsMetroNubInstalled()
489 gMetroNubEntry
= NULL
;
491 if (Gestalt(gestaltSystemVersion
, &value
) == noErr
&& value
< 0x1000)
493 /* look for MetroNub's Gestalt selector */
494 if (Gestalt(kMetroNubUserSignature
, &result
) == noErr
)
497 #if TARGET_API_MAC_CARBON
498 if (gCallUniversalProc_Proc
== NULL
)
500 CFragConnectionID connectionID
;
503 ProcPtr symbolAddress
;
505 CFragSymbolClass symbolClass
;
507 symbolAddress
= NULL
;
508 err
= GetSharedLibrary("\pInterfaceLib", kPowerPCCFragArch
, kFindCFrag
,
509 &connectionID
, &mainAddress
, errorString
);
513 gCallUniversalProc_Proc
= NULL
;
517 err
= FindSymbol(connectionID
, "\pCallUniversalProc",
518 (Ptr
*) &gCallUniversalProc_Proc
, &symbolClass
);
522 gCallUniversalProc_Proc
= NULL
;
529 MetroNubUserEntryBlock
* block
= (MetroNubUserEntryBlock
*)result
;
531 /* make sure the version of the API is compatible */
532 if (block
->apiLowVersion
<= kMetroNubUserAPIVersion
&&
533 kMetroNubUserAPIVersion
<= block
->apiHiVersion
)
534 gMetroNubEntry
= block
; /* success! */
543 #if TARGET_API_MAC_CARBON
544 return (gMetroNubEntry
!= NULL
&& gCallUniversalProc_Proc
!= NULL
);
546 return (gMetroNubEntry
!= NULL
);
550 /* ---------------------------------------------------------------------------
551 IsMWDebuggerRunning [v1 API]
552 --------------------------------------------------------------------------- */
554 Boolean
IsMWDebuggerRunning()
556 if (IsMetroNubInstalled())
557 return CallIsDebuggerRunningProc(gMetroNubEntry
->isDebuggerRunning
);
562 /* ---------------------------------------------------------------------------
563 AmIBeingMWDebugged [v1 API]
564 --------------------------------------------------------------------------- */
566 Boolean
AmIBeingMWDebugged()
568 if (IsMetroNubInstalled())
569 return CallAmIBeingDebuggedProc(gMetroNubEntry
->amIBeingDebugged
);
574 /* ---------------------------------------------------------------------------
575 UserSetWatchPoint [v2 API]
576 --------------------------------------------------------------------------- */
578 OSErr
UserSetWatchPoint (Ptr address
, long length
, WatchPointIDT
* watchPointID
)
580 if (IsMetroNubInstalled() && IsCompatibleVersion(kMetroNubUserAPIVersion
))
581 return CallUserSetWatchPointProc(gMetroNubEntry
->userSetWatchPoint
,
582 address
, length
, watchPointID
);
584 return errProcessIsNotClient
;
587 /* ---------------------------------------------------------------------------
588 ClearWatchPoint [v2 API]
589 --------------------------------------------------------------------------- */
591 OSErr
ClearWatchPoint (WatchPointIDT watchPointID
)
593 if (IsMetroNubInstalled() && IsCompatibleVersion(kMetroNubUserAPIVersion
))
594 return CallClearWatchPointProc(gMetroNubEntry
->clearWatchPoint
,
597 return errProcessIsNotClient
;
606 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
612 fputs(str
.mb_str(), m_fp
);
613 fputc(_T('\n'), m_fp
);
616 // under Windows, programs usually don't have stderr at all, so show the
617 // messages also under debugger - unless it's a console program
618 #if defined(__WXMSW__) && wxUSE_GUI && !defined(__WXMICROWIN__)
620 OutputDebugString(str
.c_str());
622 #if defined(__WXMAC__) && !defined(__DARWIN__) && wxUSE_GUI
624 strcpy( (char*) pstr
, str
.c_str() ) ;
625 strcat( (char*) pstr
, ";g" ) ;
626 c2pstr( (char*) pstr
) ;
628 Boolean running
= false ;
630 if ( IsMWDebuggerRunning() && AmIBeingMWDebugged() )
646 // ----------------------------------------------------------------------------
647 // wxLogStream implementation
648 // ----------------------------------------------------------------------------
650 #if wxUSE_STD_IOSTREAM
651 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
654 m_ostr
= &wxSTD cerr
;
659 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
663 (*m_ostr
) << str
<< wxConvertWX2MB(szString
) << wxSTD endl
;
665 #endif // wxUSE_STD_IOSTREAM
667 // ----------------------------------------------------------------------------
669 // ----------------------------------------------------------------------------
671 wxLogChain::wxLogChain(wxLog
*logger
)
674 m_logOld
= wxLog::SetActiveTarget(this);
677 void wxLogChain::SetLog(wxLog
*logger
)
679 if ( m_logNew
!= this )
682 wxLog::SetActiveTarget(logger
);
687 void wxLogChain::Flush()
692 // be careful to avoid inifinite recursion
693 if ( m_logNew
&& m_logNew
!= this )
697 void wxLogChain::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
699 // let the previous logger show it
700 if ( m_logOld
&& IsPassingMessages() )
702 // bogus cast just to access protected DoLog
703 ((wxLogChain
*)m_logOld
)->DoLog(level
, szString
, t
);
706 if ( m_logNew
&& m_logNew
!= this )
709 ((wxLogChain
*)m_logNew
)->DoLog(level
, szString
, t
);
713 // ----------------------------------------------------------------------------
715 // ----------------------------------------------------------------------------
718 // "'this' : used in base member initializer list" - so what?
719 #pragma warning(disable:4355)
722 wxLogPassThrough::wxLogPassThrough()
728 #pragma warning(default:4355)
731 // ============================================================================
732 // Global functions/variables
733 // ============================================================================
735 // ----------------------------------------------------------------------------
737 // ----------------------------------------------------------------------------
739 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
740 bool wxLog::ms_doLog
= TRUE
;
741 bool wxLog::ms_bAutoCreate
= TRUE
;
742 bool wxLog::ms_bVerbose
= FALSE
;
744 size_t wxLog::ms_suspendCount
= 0;
747 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
749 const wxChar
*wxLog::ms_timestamp
= NULL
; // save space
752 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
753 wxArrayString
wxLog::ms_aTraceMasks
;
755 // ----------------------------------------------------------------------------
756 // stdout error logging helper
757 // ----------------------------------------------------------------------------
759 // helper function: wraps the message and justifies it under given position
760 // (looks more pretty on the terminal). Also adds newline at the end.
762 // TODO this is now disabled until I find a portable way of determining the
763 // terminal window size (ok, I found it but does anybody really cares?)
764 #ifdef LOG_PRETTY_WRAP
765 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
767 size_t nMax
= 80; // FIXME
768 size_t nStart
= strlen(pszPrefix
);
772 while ( *psz
!= '\0' ) {
773 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
777 if ( *psz
!= '\0' ) {
779 for ( n
= 0; n
< nStart
; n
++ )
782 // as we wrapped, squeeze all white space
783 while ( isspace(*psz
) )
790 #endif //LOG_PRETTY_WRAP
792 // ----------------------------------------------------------------------------
793 // error code/error message retrieval functions
794 // ----------------------------------------------------------------------------
796 // get error code from syste
797 unsigned long wxSysErrorCode()
799 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
801 return ::GetLastError();
803 // TODO what to do on Windows 3.1?
811 // get error message from system
812 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
815 nErrCode
= wxSysErrorCode();
817 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
819 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
821 // get error message from system
823 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
825 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
829 // copy it to our buffer and free memory
830 if( lpMsgBuf
!= 0 ) {
831 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
832 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
836 // returned string is capitalized and ended with '\r\n' - bad
837 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
838 size_t len
= wxStrlen(s_szBuf
);
841 if ( s_szBuf
[len
- 2] == wxT('\r') )
842 s_szBuf
[len
- 2] = wxT('\0');
846 s_szBuf
[0] = wxT('\0');
856 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
857 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
860 return strerror((int)nErrCode
);