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("Trace ("), len
);
184 len
-= 7; // strlen("Trace (")
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
);
372 DoLogString(szString
, t
);
378 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
380 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
388 // ----------------------------------------------------------------------------
389 // wxLogStderr class implementation
390 // ----------------------------------------------------------------------------
392 wxLogStderr::wxLogStderr(FILE *fp
)
400 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
406 fputs(str
.mb_str(), m_fp
);
407 fputc(_T('\n'), m_fp
);
410 // under Windows, programs usually don't have stderr at all, so show the
411 // messages also under debugger - unless it's a console program
412 #if defined(__WXMSW__) && wxUSE_GUI
413 OutputDebugString(str
+ wxT("\r\n"));
415 #if defined(__WXMAC__) && wxUSE_GUI
416 debugstr(str
+ wxT("\r\n"));
420 // ----------------------------------------------------------------------------
421 // wxLogStream implementation
422 // ----------------------------------------------------------------------------
424 #if wxUSE_STD_IOSTREAM
425 wxLogStream::wxLogStream(ostream
*ostr
)
433 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
435 (*m_ostr
) << wxConvertWX2MB(szString
) << endl
;
437 #endif // wxUSE_STD_IOSTREAM
439 // ============================================================================
440 // Global functions/variables
441 // ============================================================================
443 // ----------------------------------------------------------------------------
445 // ----------------------------------------------------------------------------
447 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
448 bool wxLog::ms_doLog
= TRUE
;
449 bool wxLog::ms_bAutoCreate
= TRUE
;
452 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
454 const wxChar
*wxLog::ms_timestamp
= NULL
; // save space
457 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
458 wxArrayString
wxLog::ms_aTraceMasks
;
460 // ----------------------------------------------------------------------------
461 // stdout error logging helper
462 // ----------------------------------------------------------------------------
464 // helper function: wraps the message and justifies it under given position
465 // (looks more pretty on the terminal). Also adds newline at the end.
467 // TODO this is now disabled until I find a portable way of determining the
468 // terminal window size (ok, I found it but does anybody really cares?)
469 #ifdef LOG_PRETTY_WRAP
470 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
472 size_t nMax
= 80; // FIXME
473 size_t nStart
= strlen(pszPrefix
);
477 while ( *psz
!= '\0' ) {
478 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
482 if ( *psz
!= '\0' ) {
484 for ( n
= 0; n
< nStart
; n
++ )
487 // as we wrapped, squeeze all white space
488 while ( isspace(*psz
) )
495 #endif //LOG_PRETTY_WRAP
497 // ----------------------------------------------------------------------------
498 // error code/error message retrieval functions
499 // ----------------------------------------------------------------------------
501 // get error code from syste
502 unsigned long wxSysErrorCode()
506 return ::GetLastError();
508 // TODO what to do on Windows 3.1?
516 // get error message from system
517 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
520 nErrCode
= wxSysErrorCode();
524 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
526 // get error message from system
528 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
530 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
534 // copy it to our buffer and free memory
535 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
536 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
539 // returned string is capitalized and ended with '\r\n' - bad
540 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
541 size_t len
= wxStrlen(s_szBuf
);
544 if ( s_szBuf
[len
- 2] == wxT('\r') )
545 s_szBuf
[len
- 2] = wxT('\0');
555 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
556 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
559 return strerror((int)nErrCode
);
564 // ----------------------------------------------------------------------------
566 // ----------------------------------------------------------------------------
570 // break into the debugger
575 #elif defined(__WXMAC__)
581 #elif defined(__UNIX__)
588 // this function is called when an assert fails
589 void wxOnAssert(const wxChar
*szFile
, int nLine
, const wxChar
*szMsg
)
591 // this variable can be set to true to suppress "assert failure" messages
592 static bool s_bNoAsserts
= FALSE
;
593 static bool s_bInAssert
= FALSE
; // FIXME MT-unsafe
596 // He-e-e-e-elp!! we're trapped in endless loop
606 wxChar szBuf
[LOG_BUFFER_SIZE
];
608 // make life easier for people using VC++ IDE: clicking on the message
609 // will take us immediately to the place of the failed assert
610 wxSnprintf(szBuf
, WXSIZEOF(szBuf
),
612 wxT("%s(%d): assert failed"),
614 // make the error message more clear for all the others
615 wxT("Assert failed in file %s at line %d"),
619 if ( szMsg
!= NULL
) {
620 wxStrcat(szBuf
, wxT(": "));
621 wxStrcat(szBuf
, szMsg
);
624 wxStrcat(szBuf
, wxT("."));
627 if ( !s_bNoAsserts
) {
628 // send it to the normal log destination
631 #if wxUSE_GUI || defined(__WXMSW__)
632 // this message is intentionally not translated - it is for
634 wxStrcat(szBuf
, wxT("\nDo you want to stop the program?"
635 "\nYou can also choose [Cancel] to suppress "
636 "further warnings."));
639 switch ( wxMessageBox(szBuf
, "Debug",
640 wxYES_NO
| wxCANCEL
| wxICON_STOP
) ) {
649 //case wxNO: nothing to do
651 #else // !GUI, but MSW
652 switch ( ::MessageBox(NULL
, szBuf
, "Debug",
653 MB_YESNOCANCEL
| MB_ICONSTOP
) ) {
662 //case IDNO: nothing to do