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 strncpy(s_szBuf
, _T("("), len
);
184 len
-= 2; // strlen("(")
186 strncat(p
, mask
, len
);
187 size_t lenMask
= wxStrlen(mask
);
191 strncat(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 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
411 fputs(str
.mb_str(), m_fp
);
412 fputc(_T('\n'), m_fp
);
415 // under Windows, programs usually don't have stderr at all, so show the
416 // messages also under debugger - unless it's a console program
417 #if defined(__WXMSW__) && wxUSE_GUI
418 OutputDebugString(str
+ wxT("\r\n"));
420 #if defined(__WXMAC__) && wxUSE_GUI
421 debugstr(str
+ wxT("\r\n"));
425 // ----------------------------------------------------------------------------
426 // wxLogStream implementation
427 // ----------------------------------------------------------------------------
429 #if wxUSE_STD_IOSTREAM
430 wxLogStream::wxLogStream(ostream
*ostr
)
438 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
440 (*m_ostr
) << wxConvertWX2MB(szString
) << endl
;
442 #endif // wxUSE_STD_IOSTREAM
444 // ============================================================================
445 // Global functions/variables
446 // ============================================================================
448 // ----------------------------------------------------------------------------
450 // ----------------------------------------------------------------------------
452 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
453 bool wxLog::ms_doLog
= TRUE
;
454 bool wxLog::ms_bAutoCreate
= TRUE
;
456 size_t wxLog::ms_suspendCount
= 0;
459 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
461 const wxChar
*wxLog::ms_timestamp
= NULL
; // save space
464 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
465 wxArrayString
wxLog::ms_aTraceMasks
;
467 // ----------------------------------------------------------------------------
468 // stdout error logging helper
469 // ----------------------------------------------------------------------------
471 // helper function: wraps the message and justifies it under given position
472 // (looks more pretty on the terminal). Also adds newline at the end.
474 // TODO this is now disabled until I find a portable way of determining the
475 // terminal window size (ok, I found it but does anybody really cares?)
476 #ifdef LOG_PRETTY_WRAP
477 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
479 size_t nMax
= 80; // FIXME
480 size_t nStart
= strlen(pszPrefix
);
484 while ( *psz
!= '\0' ) {
485 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
489 if ( *psz
!= '\0' ) {
491 for ( n
= 0; n
< nStart
; n
++ )
494 // as we wrapped, squeeze all white space
495 while ( isspace(*psz
) )
502 #endif //LOG_PRETTY_WRAP
504 // ----------------------------------------------------------------------------
505 // error code/error message retrieval functions
506 // ----------------------------------------------------------------------------
508 // get error code from syste
509 unsigned long wxSysErrorCode()
513 return ::GetLastError();
515 // TODO what to do on Windows 3.1?
523 // get error message from system
524 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
527 nErrCode
= wxSysErrorCode();
531 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
533 // get error message from system
535 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
537 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
541 // copy it to our buffer and free memory
542 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
543 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
546 // returned string is capitalized and ended with '\r\n' - bad
547 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
548 size_t len
= wxStrlen(s_szBuf
);
551 if ( s_szBuf
[len
- 2] == wxT('\r') )
552 s_szBuf
[len
- 2] = wxT('\0');
562 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
563 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
566 return strerror((int)nErrCode
);
571 // ----------------------------------------------------------------------------
573 // ----------------------------------------------------------------------------
577 // break into the debugger
582 #elif defined(__WXMAC__)
588 #elif defined(__UNIX__)
595 // this function is called when an assert fails
596 void wxOnAssert(const wxChar
*szFile
, int nLine
, const wxChar
*szMsg
)
598 // this variable can be set to true to suppress "assert failure" messages
599 static bool s_bNoAsserts
= FALSE
;
600 static bool s_bInAssert
= FALSE
; // FIXME MT-unsafe
603 // He-e-e-e-elp!! we're trapped in endless loop
613 wxChar szBuf
[LOG_BUFFER_SIZE
];
615 // make life easier for people using VC++ IDE: clicking on the message
616 // will take us immediately to the place of the failed assert
617 wxSnprintf(szBuf
, WXSIZEOF(szBuf
),
619 wxT("%s(%d): assert failed"),
621 // make the error message more clear for all the others
622 wxT("Assert failed in file %s at line %d"),
626 if ( szMsg
!= NULL
) {
627 wxStrcat(szBuf
, wxT(": "));
628 wxStrcat(szBuf
, szMsg
);
631 wxStrcat(szBuf
, wxT("."));
634 if ( !s_bNoAsserts
) {
635 // send it to the normal log destination
638 #if wxUSE_GUI || defined(__WXMSW__)
639 // this message is intentionally not translated - it is for
641 wxStrcat(szBuf
, wxT("\nDo you want to stop the program?"
642 "\nYou can also choose [Cancel] to suppress "
643 "further warnings."));
646 switch ( wxMessageBox(szBuf
, "Debug",
647 wxYES_NO
| wxCANCEL
| wxICON_STOP
) ) {
656 //case wxNO: nothing to do
658 #else // !GUI, but MSW
659 switch ( ::MessageBox(NULL
, szBuf
, "Debug",
660 MB_YESNOCANCEL
| MB_ICONSTOP
) ) {
669 //case IDNO: nothing to do