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"
53 // other standard headers
59 #include "wx/msw/private.h" // includes windows.h for OutputDebugString
64 // ----------------------------------------------------------------------------
65 // non member functions
66 // ----------------------------------------------------------------------------
68 // define this to enable wrapping of log messages
69 //#define LOG_PRETTY_WRAP
71 #ifdef LOG_PRETTY_WRAP
72 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
75 // ============================================================================
77 // ============================================================================
79 // ----------------------------------------------------------------------------
81 // ----------------------------------------------------------------------------
83 // log functions can't allocate memory (LogError("out of memory...") should
84 // work!), so we use a static buffer for all log messages
85 #define LOG_BUFFER_SIZE (4096)
87 // static buffer for error messages
88 static wxChar s_szBuf
[LOG_BUFFER_SIZE
];
92 // the critical section protecting the static buffer
93 static wxCriticalSection gs_csLogBuf
;
95 #endif // wxUSE_THREADS
97 // ----------------------------------------------------------------------------
98 // implementation of Log functions
100 // NB: unfortunately we need all these distinct functions, we can't make them
101 // macros and not all compilers inline vararg functions.
102 // ----------------------------------------------------------------------------
104 // generic log function
105 void wxLogGeneric(wxLogLevel level
, const wxChar
*szFormat
, ...)
107 if ( wxLog::GetActiveTarget() != NULL
) {
108 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
111 va_start(argptr
, szFormat
);
112 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
115 wxLog::OnLog(level
, s_szBuf
, time(NULL
));
119 #define IMPLEMENT_LOG_FUNCTION(level) \
120 void wxLog##level(const wxChar *szFormat, ...) \
122 if ( wxLog::GetActiveTarget() != NULL ) { \
123 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
126 va_start(argptr, szFormat); \
127 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
130 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
134 IMPLEMENT_LOG_FUNCTION(FatalError
)
135 IMPLEMENT_LOG_FUNCTION(Error
)
136 IMPLEMENT_LOG_FUNCTION(Warning
)
137 IMPLEMENT_LOG_FUNCTION(Message
)
138 IMPLEMENT_LOG_FUNCTION(Info
)
139 IMPLEMENT_LOG_FUNCTION(Status
)
141 // same as info, but only if 'verbose' mode is on
142 void wxLogVerbose(const wxChar
*szFormat
, ...)
144 wxLog
*pLog
= wxLog::GetActiveTarget();
145 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
146 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
149 va_start(argptr
, szFormat
);
150 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
153 wxLog::OnLog(wxLOG_Info
, s_szBuf
, time(NULL
));
159 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
160 void wxLog##level(const wxChar *szFormat, ...) \
162 if ( wxLog::GetActiveTarget() != NULL ) { \
163 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
166 va_start(argptr, szFormat); \
167 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
170 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
174 void wxLogTrace(const wxChar
*mask
, const wxChar
*szFormat
, ...)
176 wxLog
*pLog
= wxLog::GetActiveTarget();
178 if ( pLog
!= NULL
&& wxLog::IsAllowedTraceMask(mask
) ) {
179 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
182 size_t len
= WXSIZEOF(s_szBuf
);
183 wxStrncpy(s_szBuf
, _T("("), len
);
184 len
-= 1; // strlen("(")
186 wxStrncat(p
, mask
, len
);
187 size_t lenMask
= wxStrlen(mask
);
191 wxStrncat(p
, _T(") "), len
);
196 va_start(argptr
, szFormat
);
197 wxVsnprintf(p
, len
, szFormat
, argptr
);
200 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
204 void wxLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, ...)
206 wxLog
*pLog
= wxLog::GetActiveTarget();
208 // we check that all of mask bits are set in the current mask, so
209 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
210 // if both bits are set.
211 if ( pLog
!= NULL
&& ((pLog
->GetTraceMask() & mask
) == mask
) ) {
212 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
215 va_start(argptr
, szFormat
);
216 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
219 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
224 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
227 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
228 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
230 // wxLogSysError: one uses the last error code, for other you must give it
233 // common part of both wxLogSysError
234 void wxLogSysErrorHelper(long lErrCode
)
236 wxChar szErrMsg
[LOG_BUFFER_SIZE
/ 2];
237 wxSnprintf(szErrMsg
, WXSIZEOF(szErrMsg
),
238 _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
239 wxStrncat(s_szBuf
, szErrMsg
, WXSIZEOF(s_szBuf
) - wxStrlen(s_szBuf
));
241 wxLog::OnLog(wxLOG_Error
, s_szBuf
, time(NULL
));
244 void WXDLLEXPORT
wxLogSysError(const wxChar
*szFormat
, ...)
246 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
249 va_start(argptr
, szFormat
);
250 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
253 wxLogSysErrorHelper(wxSysErrorCode());
256 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const wxChar
*szFormat
, ...)
258 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
261 va_start(argptr
, szFormat
);
262 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
265 wxLogSysErrorHelper(lErrCode
);
268 // ----------------------------------------------------------------------------
269 // wxLog class implementation
270 // ----------------------------------------------------------------------------
274 m_bHasMessages
= FALSE
;
276 // enable verbose messages by default in the debug builds
281 #endif // debug/release
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::RemoveTraceMask(const wxString
& str
)
324 int index
= ms_aTraceMasks
.Index(str
);
325 if ( index
!= wxNOT_FOUND
)
326 ms_aTraceMasks
.Remove((size_t)index
);
329 void wxLog::TimeStamp(wxString
*str
)
335 (void)time(&timeNow
);
336 wxStrftime(buf
, WXSIZEOF(buf
), ms_timestamp
, localtime(&timeNow
));
339 *str
<< buf
<< wxT(": ");
343 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
346 case wxLOG_FatalError
:
347 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
348 DoLogString(_("Program aborted."), t
);
354 DoLogString(wxString(_("Error: ")) + szString
, t
);
358 DoLogString(wxString(_("Warning: ")) + szString
, t
);
365 default: // log unknown log levels too
366 DoLogString(szString
, t
);
373 wxString msg
= level
== wxLOG_Trace
? wxT("Trace: ")
383 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
385 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
393 // ----------------------------------------------------------------------------
394 // wxLogStderr class implementation
395 // ----------------------------------------------------------------------------
397 wxLogStderr::wxLogStderr(FILE *fp
)
405 #if defined(__WXMAC__)
406 #define kDebuggerSignature 'MWDB'
408 static Boolean
FindProcessBySignature(OSType signature
, ProcessInfoRec
* info
)
411 ProcessSerialNumber psn
;
412 Boolean found
= false;
413 psn
.highLongOfPSN
= 0;
414 psn
.lowLongOfPSN
= kNoProcess
;
416 if (!info
) return false;
418 info
->processInfoLength
= sizeof(ProcessInfoRec
);
419 info
->processName
= NULL
;
420 info
->processAppSpec
= NULL
;
423 while (!found
&& err
== noErr
)
425 err
= GetNextProcess(&psn
);
428 err
= GetProcessInformation(&psn
, info
);
429 found
= err
== noErr
&& info
->processSignature
== signature
;
435 pascal Boolean
MWDebuggerIsRunning(void)
438 return FindProcessBySignature(kDebuggerSignature
, &info
);
441 pascal OSErr
AmIBeingMWDebugged(Boolean
* result
)
444 ProcessSerialNumber psn
;
445 OSType sig
= kDebuggerSignature
;
446 AppleEvent theAE
= {typeNull
, NULL
};
447 AppleEvent theReply
= {typeNull
, NULL
};
448 AEAddressDesc addr
= {typeNull
, NULL
};
452 if (!result
) return paramErr
;
454 err
= AECreateDesc(typeApplSignature
, &sig
, sizeof(sig
), &addr
);
455 if (err
!= noErr
) goto exit
;
457 err
= AECreateAppleEvent('MWDB', 'Dbg?', &addr
,
458 kAutoGenerateReturnID
, kAnyTransactionID
, &theAE
);
459 if (err
!= noErr
) goto exit
;
461 GetCurrentProcess(&psn
);
462 err
= AEPutParamPtr(&theAE
, keyDirectObject
, typeProcessSerialNumber
,
464 if (err
!= noErr
) goto exit
;
466 err
= AESend(&theAE
, &theReply
, kAEWaitReply
, kAENormalPriority
,
467 kAEDefaultTimeout
, NULL
, NULL
);
468 if (err
!= noErr
) goto exit
;
470 err
= AEGetParamPtr(&theReply
, keyAEResult
, typeBoolean
, &actualType
, result
,
471 sizeof(Boolean
), &actualSize
);
475 AEDisposeDesc(&addr
);
476 if (theAE
.dataHandle
)
477 AEDisposeDesc(&theAE
);
478 if (theReply
.dataHandle
)
479 AEDisposeDesc(&theReply
);
485 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
491 fputs(str
.mb_str(), m_fp
);
492 fputc(_T('\n'), m_fp
);
495 // under Windows, programs usually don't have stderr at all, so show the
496 // messages also under debugger - unless it's a console program
497 #if defined(__WXMSW__) && wxUSE_GUI
499 OutputDebugString(str
.c_str());
501 #if defined(__WXMAC__) && wxUSE_GUI
503 strcpy( (char*) pstr
, str
.c_str() ) ;
504 strcat( (char*) pstr
, ";g" ) ;
505 c2pstr( (char*) pstr
) ;
507 Boolean running
= false ;
510 if ( MWDebuggerIsRunning() )
512 AmIBeingMWDebugged( &running ) ;
535 // ----------------------------------------------------------------------------
536 // wxLogStream implementation
537 // ----------------------------------------------------------------------------
539 #if wxUSE_STD_IOSTREAM
540 wxLogStream::wxLogStream(ostream
*ostr
)
548 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
550 (*m_ostr
) << wxConvertWX2MB(szString
) << endl
;
552 #endif // wxUSE_STD_IOSTREAM
554 // ============================================================================
555 // Global functions/variables
556 // ============================================================================
558 // ----------------------------------------------------------------------------
560 // ----------------------------------------------------------------------------
562 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
563 bool wxLog::ms_doLog
= TRUE
;
564 bool wxLog::ms_bAutoCreate
= TRUE
;
566 size_t wxLog::ms_suspendCount
= 0;
569 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
571 const wxChar
*wxLog::ms_timestamp
= NULL
; // save space
574 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
575 wxArrayString
wxLog::ms_aTraceMasks
;
577 // ----------------------------------------------------------------------------
578 // stdout error logging helper
579 // ----------------------------------------------------------------------------
581 // helper function: wraps the message and justifies it under given position
582 // (looks more pretty on the terminal). Also adds newline at the end.
584 // TODO this is now disabled until I find a portable way of determining the
585 // terminal window size (ok, I found it but does anybody really cares?)
586 #ifdef LOG_PRETTY_WRAP
587 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
589 size_t nMax
= 80; // FIXME
590 size_t nStart
= strlen(pszPrefix
);
594 while ( *psz
!= '\0' ) {
595 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
599 if ( *psz
!= '\0' ) {
601 for ( n
= 0; n
< nStart
; n
++ )
604 // as we wrapped, squeeze all white space
605 while ( isspace(*psz
) )
612 #endif //LOG_PRETTY_WRAP
614 // ----------------------------------------------------------------------------
615 // error code/error message retrieval functions
616 // ----------------------------------------------------------------------------
618 // get error code from syste
619 unsigned long wxSysErrorCode()
623 return ::GetLastError();
625 // TODO what to do on Windows 3.1?
633 // get error message from system
634 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
637 nErrCode
= wxSysErrorCode();
641 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
643 // get error message from system
645 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
647 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
651 // copy it to our buffer and free memory
652 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
653 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
656 // returned string is capitalized and ended with '\r\n' - bad
657 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
658 size_t len
= wxStrlen(s_szBuf
);
661 if ( s_szBuf
[len
- 2] == wxT('\r') )
662 s_szBuf
[len
- 2] = wxT('\0');
672 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
673 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
676 return strerror((int)nErrCode
);
681 // ----------------------------------------------------------------------------
683 // ----------------------------------------------------------------------------
687 // break into the debugger
692 #elif defined(__WXMAC__)
698 #elif defined(__UNIX__)
705 // this function is called when an assert fails
706 void wxOnAssert(const wxChar
*szFile
, int nLine
, const wxChar
*szMsg
)
708 // this variable can be set to true to suppress "assert failure" messages
709 static bool s_bNoAsserts
= FALSE
;
710 static bool s_bInAssert
= FALSE
; // FIXME MT-unsafe
713 // He-e-e-e-elp!! we're trapped in endless loop
723 wxChar szBuf
[LOG_BUFFER_SIZE
];
725 // make life easier for people using VC++ IDE: clicking on the message
726 // will take us immediately to the place of the failed assert
727 wxSnprintf(szBuf
, WXSIZEOF(szBuf
),
729 wxT("%s(%d): assert failed"),
731 // make the error message more clear for all the others
732 wxT("Assert failed in file %s at line %d"),
736 if ( szMsg
!= NULL
) {
737 wxStrcat(szBuf
, wxT(": "));
738 wxStrcat(szBuf
, szMsg
);
741 wxStrcat(szBuf
, wxT("."));
744 if ( !s_bNoAsserts
) {
745 // send it to the normal log destination
748 #if wxUSE_GUI || defined(__WXMSW__)
749 // this message is intentionally not translated - it is for
751 wxStrcat(szBuf
, wxT("\nDo you want to stop the program?\nYou can also choose [Cancel] to suppress further warnings."));
754 switch ( wxMessageBox(szBuf
, wxT("Debug"),
755 wxYES_NO
| wxCANCEL
| wxICON_STOP
) ) {
764 //case wxNO: nothing to do
766 #else // !GUI, but MSW
767 switch ( ::MessageBox(NULL
, szBuf
, _T("Debug"),
768 MB_YESNOCANCEL
| MB_ICONSTOP
) ) {
777 //case IDNO: nothing to do