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"
42 #include "wx/msgdlg.h"
47 #include "wx/textfile.h"
49 #include "wx/wxchar.h"
51 #include "wx/thread.h"
55 // other standard headers
61 #include "wx/msw/private.h" // includes windows.h for OutputDebugString
66 // ----------------------------------------------------------------------------
67 // non member functions
68 // ----------------------------------------------------------------------------
70 // define this to enable wrapping of log messages
71 //#define LOG_PRETTY_WRAP
73 #ifdef LOG_PRETTY_WRAP
74 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
77 // ============================================================================
79 // ============================================================================
81 // ----------------------------------------------------------------------------
83 // ----------------------------------------------------------------------------
85 // log functions can't allocate memory (LogError("out of memory...") should
86 // work!), so we use a static buffer for all log messages
87 #define LOG_BUFFER_SIZE (4096)
89 // static buffer for error messages
90 static wxChar s_szBuf
[LOG_BUFFER_SIZE
];
94 // the critical section protecting the static buffer
95 static wxCriticalSection gs_csLogBuf
;
97 #endif // wxUSE_THREADS
99 // ----------------------------------------------------------------------------
100 // implementation of Log functions
102 // NB: unfortunately we need all these distinct functions, we can't make them
103 // macros and not all compilers inline vararg functions.
104 // ----------------------------------------------------------------------------
106 // generic log function
107 void wxLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, ...)
109 if ( wxLog::GetActiveTarget() != NULL
) {
110 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
113 va_start(argptr
, szFormat
);
114 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
117 wxLog::OnLog(level
, s_szBuf
, time(NULL
));
121 #define IMPLEMENT_LOG_FUNCTION(level) \
122 void wxLog##level(const wxChar *szFormat, ...) \
124 if ( wxLog::GetActiveTarget() != NULL ) { \
125 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
128 va_start(argptr, szFormat); \
129 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
132 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
136 IMPLEMENT_LOG_FUNCTION(FatalError
)
137 IMPLEMENT_LOG_FUNCTION(Error
)
138 IMPLEMENT_LOG_FUNCTION(Warning
)
139 IMPLEMENT_LOG_FUNCTION(Message
)
140 IMPLEMENT_LOG_FUNCTION(Info
)
141 IMPLEMENT_LOG_FUNCTION(Status
)
143 // same as info, but only if 'verbose' mode is on
144 void wxLogVerbose(const wxChar
*szFormat
, ...)
146 wxLog
*pLog
= wxLog::GetActiveTarget();
147 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
148 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
151 va_start(argptr
, szFormat
);
152 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
155 wxLog::OnLog(wxLOG_Info
, s_szBuf
, time(NULL
));
161 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
162 void wxLog##level(const wxChar *szFormat, ...) \
164 if ( wxLog::GetActiveTarget() != NULL ) { \
165 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
168 va_start(argptr, szFormat); \
169 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
172 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
176 void wxLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, ...)
178 wxLog
*pLog
= wxLog::GetActiveTarget();
180 if ( pLog
!= NULL
&& wxLog::IsAllowedTraceMask(mask
) ) {
181 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
184 size_t len
= WXSIZEOF(s_szBuf
);
185 wxStrncpy(s_szBuf
, _T("("), len
);
186 len
-= 1; // strlen("(")
188 wxStrncat(p
, mask
, len
);
189 size_t lenMask
= wxStrlen(mask
);
193 wxStrncat(p
, _T(") "), len
);
198 va_start(argptr
, szFormat
);
199 wxVsnprintf(p
, len
, szFormat
, argptr
);
202 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
206 void wxLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, ...)
208 wxLog
*pLog
= wxLog::GetActiveTarget();
210 // we check that all of mask bits are set in the current mask, so
211 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
212 // if both bits are set.
213 if ( pLog
!= NULL
&& ((pLog
->GetTraceMask() & mask
) == mask
) ) {
214 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
217 va_start(argptr
, szFormat
);
218 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
221 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
226 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
229 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
230 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
232 // wxLogSysError: one uses the last error code, for other you must give it
235 // common part of both wxLogSysError
236 void wxLogSysErrorHelper(long lErrCode
)
238 wxChar szErrMsg
[LOG_BUFFER_SIZE
/ 2];
239 wxSnprintf(szErrMsg
, WXSIZEOF(szErrMsg
),
240 _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
241 wxStrncat(s_szBuf
, szErrMsg
, WXSIZEOF(s_szBuf
) - wxStrlen(s_szBuf
));
243 wxLog::OnLog(wxLOG_Error
, s_szBuf
, time(NULL
));
246 void WXDLLEXPORT
wxLogSysError(const wxChar
*szFormat
, ...)
248 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
251 va_start(argptr
, szFormat
);
252 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
255 wxLogSysErrorHelper(wxSysErrorCode());
258 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const wxChar
*szFormat
, ...)
260 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
263 va_start(argptr
, szFormat
);
264 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
267 wxLogSysErrorHelper(lErrCode
);
270 // ----------------------------------------------------------------------------
271 // wxLog class implementation
272 // ----------------------------------------------------------------------------
276 m_bHasMessages
= FALSE
;
278 // enable verbose messages by default in the debug builds
283 #endif // debug/release
286 wxLog
*wxLog::GetActiveTarget()
288 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
289 // prevent infinite recursion if someone calls wxLogXXX() from
290 // wxApp::CreateLogTarget()
291 static bool s_bInGetActiveTarget
= FALSE
;
292 if ( !s_bInGetActiveTarget
) {
293 s_bInGetActiveTarget
= TRUE
;
295 // ask the application to create a log target for us
296 if ( wxTheApp
!= NULL
)
297 ms_pLogger
= wxTheApp
->CreateLogTarget();
299 ms_pLogger
= new wxLogStderr
;
301 s_bInGetActiveTarget
= FALSE
;
303 // do nothing if it fails - what can we do?
310 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
312 if ( ms_pLogger
!= NULL
) {
313 // flush the old messages before changing because otherwise they might
314 // get lost later if this target is not restored
318 wxLog
*pOldLogger
= ms_pLogger
;
319 ms_pLogger
= pLogger
;
324 void wxLog::RemoveTraceMask(const wxString
& str
)
326 int index
= ms_aTraceMasks
.Index(str
);
327 if ( index
!= wxNOT_FOUND
)
328 ms_aTraceMasks
.Remove((size_t)index
);
331 void wxLog::TimeStamp(wxString
*str
)
337 (void)time(&timeNow
);
338 wxStrftime(buf
, WXSIZEOF(buf
), ms_timestamp
, localtime(&timeNow
));
341 *str
<< buf
<< wxT(": ");
345 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
348 case wxLOG_FatalError
:
349 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
350 DoLogString(_("Program aborted."), t
);
356 DoLogString(wxString(_("Error: ")) + szString
, t
);
360 DoLogString(wxString(_("Warning: ")) + szString
, t
);
367 default: // log unknown log levels too
368 DoLogString(szString
, t
);
375 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
385 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
387 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
395 // ----------------------------------------------------------------------------
396 // wxLogStderr class implementation
397 // ----------------------------------------------------------------------------
399 wxLogStderr::wxLogStderr(FILE *fp
)
407 #if defined(__WXMAC__)
408 #define kDebuggerSignature 'MWDB'
410 static Boolean
FindProcessBySignature(OSType signature
, ProcessInfoRec
* info
)
413 ProcessSerialNumber psn
;
414 Boolean found
= false;
415 psn
.highLongOfPSN
= 0;
416 psn
.lowLongOfPSN
= kNoProcess
;
418 if (!info
) return false;
420 info
->processInfoLength
= sizeof(ProcessInfoRec
);
421 info
->processName
= NULL
;
422 info
->processAppSpec
= NULL
;
425 while (!found
&& err
== noErr
)
427 err
= GetNextProcess(&psn
);
430 err
= GetProcessInformation(&psn
, info
);
431 found
= err
== noErr
&& info
->processSignature
== signature
;
437 pascal Boolean
MWDebuggerIsRunning(void)
440 return FindProcessBySignature(kDebuggerSignature
, &info
);
443 pascal OSErr
AmIBeingMWDebugged(Boolean
* result
)
446 ProcessSerialNumber psn
;
447 OSType sig
= kDebuggerSignature
;
448 AppleEvent theAE
= {typeNull
, NULL
};
449 AppleEvent theReply
= {typeNull
, NULL
};
450 AEAddressDesc addr
= {typeNull
, NULL
};
454 if (!result
) return paramErr
;
456 err
= AECreateDesc(typeApplSignature
, &sig
, sizeof(sig
), &addr
);
457 if (err
!= noErr
) goto exit
;
459 err
= AECreateAppleEvent('MWDB', 'Dbg?', &addr
,
460 kAutoGenerateReturnID
, kAnyTransactionID
, &theAE
);
461 if (err
!= noErr
) goto exit
;
463 GetCurrentProcess(&psn
);
464 err
= AEPutParamPtr(&theAE
, keyDirectObject
, typeProcessSerialNumber
,
466 if (err
!= noErr
) goto exit
;
468 err
= AESend(&theAE
, &theReply
, kAEWaitReply
, kAENormalPriority
,
469 kAEDefaultTimeout
, NULL
, NULL
);
470 if (err
!= noErr
) goto exit
;
472 err
= AEGetParamPtr(&theReply
, keyAEResult
, typeBoolean
, &actualType
, result
,
473 sizeof(Boolean
), &actualSize
);
477 AEDisposeDesc(&addr
);
478 if (theAE
.dataHandle
)
479 AEDisposeDesc(&theAE
);
480 if (theReply
.dataHandle
)
481 AEDisposeDesc(&theReply
);
487 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
493 fputs(str
.mb_str(), m_fp
);
494 fputc(_T('\n'), m_fp
);
497 // under Windows, programs usually don't have stderr at all, so show the
498 // messages also under debugger - unless it's a console program
499 #if defined(__WXMSW__) && wxUSE_GUI
501 OutputDebugString(str
.c_str());
503 #if defined(__WXMAC__) && wxUSE_GUI
505 strcpy( (char*) pstr
, str
.c_str() ) ;
506 strcat( (char*) pstr
, ";g" ) ;
507 c2pstr( (char*) pstr
) ;
509 Boolean running
= false ;
512 if ( MWDebuggerIsRunning() )
514 AmIBeingMWDebugged( &running ) ;
537 // ----------------------------------------------------------------------------
538 // wxLogStream implementation
539 // ----------------------------------------------------------------------------
541 #if wxUSE_STD_IOSTREAM
542 wxLogStream::wxLogStream(ostream
*ostr
)
550 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
552 (*m_ostr
) << wxConvertWX2MB(szString
) << endl
;
554 #endif // wxUSE_STD_IOSTREAM
556 // ============================================================================
557 // Global functions/variables
558 // ============================================================================
560 // ----------------------------------------------------------------------------
562 // ----------------------------------------------------------------------------
564 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
565 bool wxLog::ms_doLog
= TRUE
;
566 bool wxLog::ms_bAutoCreate
= TRUE
;
568 size_t wxLog::ms_suspendCount
= 0;
571 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
573 const wxChar
*wxLog::ms_timestamp
= NULL
; // save space
576 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
577 wxArrayString
wxLog::ms_aTraceMasks
;
579 // ----------------------------------------------------------------------------
580 // stdout error logging helper
581 // ----------------------------------------------------------------------------
583 // helper function: wraps the message and justifies it under given position
584 // (looks more pretty on the terminal). Also adds newline at the end.
586 // TODO this is now disabled until I find a portable way of determining the
587 // terminal window size (ok, I found it but does anybody really cares?)
588 #ifdef LOG_PRETTY_WRAP
589 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
591 size_t nMax
= 80; // FIXME
592 size_t nStart
= strlen(pszPrefix
);
596 while ( *psz
!= '\0' ) {
597 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
601 if ( *psz
!= '\0' ) {
603 for ( n
= 0; n
< nStart
; n
++ )
606 // as we wrapped, squeeze all white space
607 while ( isspace(*psz
) )
614 #endif //LOG_PRETTY_WRAP
616 // ----------------------------------------------------------------------------
617 // error code/error message retrieval functions
618 // ----------------------------------------------------------------------------
620 // get error code from syste
621 unsigned long wxSysErrorCode()
625 return ::GetLastError();
627 // TODO what to do on Windows 3.1?
635 // get error message from system
636 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
639 nErrCode
= wxSysErrorCode();
643 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
645 // get error message from system
647 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
649 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
653 // copy it to our buffer and free memory
654 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
655 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
658 // returned string is capitalized and ended with '\r\n' - bad
659 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
660 size_t len
= wxStrlen(s_szBuf
);
663 if ( s_szBuf
[len
- 2] == wxT('\r') )
664 s_szBuf
[len
- 2] = wxT('\0');
674 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
675 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
678 return strerror((int)nErrCode
);
683 // ----------------------------------------------------------------------------
685 // ----------------------------------------------------------------------------
689 // break into the debugger
694 #elif defined(__WXMAC__)
700 #elif defined(__UNIX__)
707 // this function is called when an assert fails
708 void wxOnAssert(const wxChar
*szFile
, int nLine
, const wxChar
*szMsg
)
710 // this variable can be set to true to suppress "assert failure" messages
711 static bool s_bNoAsserts
= FALSE
;
712 static bool s_bInAssert
= FALSE
; // FIXME MT-unsafe
715 // He-e-e-e-elp!! we're trapped in endless loop
725 wxChar szBuf
[LOG_BUFFER_SIZE
];
727 // make life easier for people using VC++ IDE: clicking on the message
728 // will take us immediately to the place of the failed assert
729 wxSnprintf(szBuf
, WXSIZEOF(szBuf
),
731 wxT("%s(%d): assert failed"),
733 // make the error message more clear for all the others
734 wxT("Assert failed in file %s at line %d"),
738 if ( szMsg
!= NULL
) {
739 wxStrcat(szBuf
, wxT(": "));
740 wxStrcat(szBuf
, szMsg
);
743 wxStrcat(szBuf
, wxT("."));
746 if ( !s_bNoAsserts
) {
747 // send it to the normal log destination
750 #if wxUSE_GUI || defined(__WXMSW__)
751 // this message is intentionally not translated - it is for
753 wxStrcat(szBuf
, wxT("\nDo you want to stop the program?\nYou can also choose [Cancel] to suppress further warnings."));
755 // use the native message box if available: this is more robust than
758 switch ( ::MessageBox(NULL
, szBuf
, _T("Debug"),
759 MB_YESNOCANCEL
| MB_ICONSTOP
) ) {
768 //case IDNO: nothing to do
771 switch ( wxMessageBox(szBuf
, wxT("Debug"),
772 wxYES_NO
| wxCANCEL
| wxICON_STOP
) ) {
781 //case wxNO: nothing to do