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 va_start(argptr
, szFormat
);
183 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
186 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
190 void wxLogTrace(wxTraceMask mask
, const wxChar
*szFormat
, ...)
192 wxLog
*pLog
= wxLog::GetActiveTarget();
194 // we check that all of mask bits are set in the current mask, so
195 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
196 // if both bits are set.
197 if ( pLog
!= NULL
&& ((pLog
->GetTraceMask() & mask
) == mask
) ) {
198 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
201 va_start(argptr
, szFormat
);
202 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
205 wxLog::OnLog(wxLOG_Trace
, s_szBuf
, time(NULL
));
210 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
213 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
214 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
216 // wxLogSysError: one uses the last error code, for other you must give it
219 // common part of both wxLogSysError
220 void wxLogSysErrorHelper(long lErrCode
)
222 wxChar szErrMsg
[LOG_BUFFER_SIZE
/ 2];
223 wxSnprintf(szErrMsg
, WXSIZEOF(szErrMsg
),
224 _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
225 wxStrncat(s_szBuf
, szErrMsg
, WXSIZEOF(s_szBuf
) - wxStrlen(s_szBuf
));
227 wxLog::OnLog(wxLOG_Error
, s_szBuf
, time(NULL
));
230 void WXDLLEXPORT
wxLogSysError(const wxChar
*szFormat
, ...)
232 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
235 va_start(argptr
, szFormat
);
236 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
239 wxLogSysErrorHelper(wxSysErrorCode());
242 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const wxChar
*szFormat
, ...)
244 wxCRIT_SECT_LOCKER(locker
, gs_csLogBuf
);
247 va_start(argptr
, szFormat
);
248 wxVsnprintf(s_szBuf
, WXSIZEOF(s_szBuf
), szFormat
, argptr
);
251 wxLogSysErrorHelper(lErrCode
);
254 // ----------------------------------------------------------------------------
255 // wxLog class implementation
256 // ----------------------------------------------------------------------------
260 m_bHasMessages
= FALSE
;
262 // enable verbose messages by default in the debug builds
267 #endif // debug/release
270 wxLog
*wxLog::GetActiveTarget()
272 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
273 // prevent infinite recursion if someone calls wxLogXXX() from
274 // wxApp::CreateLogTarget()
275 static bool s_bInGetActiveTarget
= FALSE
;
276 if ( !s_bInGetActiveTarget
) {
277 s_bInGetActiveTarget
= TRUE
;
279 // ask the application to create a log target for us
280 if ( wxTheApp
!= NULL
)
281 ms_pLogger
= wxTheApp
->CreateLogTarget();
283 ms_pLogger
= new wxLogStderr
;
285 s_bInGetActiveTarget
= FALSE
;
287 // do nothing if it fails - what can we do?
294 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
296 if ( ms_pLogger
!= NULL
) {
297 // flush the old messages before changing because otherwise they might
298 // get lost later if this target is not restored
302 wxLog
*pOldLogger
= ms_pLogger
;
303 ms_pLogger
= pLogger
;
308 void wxLog::RemoveTraceMask(const wxString
& str
)
310 int index
= ms_aTraceMasks
.Index(str
);
311 if ( index
!= wxNOT_FOUND
)
312 ms_aTraceMasks
.Remove((size_t)index
);
315 void wxLog::TimeStamp(wxString
*str
)
321 (void)time(&timeNow
);
322 wxStrftime(buf
, WXSIZEOF(buf
), ms_timestamp
, localtime(&timeNow
));
325 *str
<< buf
<< wxT(": ");
329 void wxLog::DoLog(wxLogLevel level
, const wxChar
*szString
, time_t t
)
332 case wxLOG_FatalError
:
333 DoLogString(wxString(_("Fatal error: ")) + szString
, t
);
334 DoLogString(_("Program aborted."), t
);
340 DoLogString(wxString(_("Error: ")) + szString
, t
);
344 DoLogString(wxString(_("Warning: ")) + szString
, t
);
351 default: // log unknown log levels too
352 DoLogString(szString
, t
);
358 DoLogString(szString
, t
);
364 void wxLog::DoLogString(const wxChar
*WXUNUSED(szString
), time_t WXUNUSED(t
))
366 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
374 // ----------------------------------------------------------------------------
375 // wxLogStderr class implementation
376 // ----------------------------------------------------------------------------
378 wxLogStderr::wxLogStderr(FILE *fp
)
386 void wxLogStderr::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
392 fputs(str
.mb_str(), m_fp
);
393 fputc(_T('\n'), m_fp
);
396 // under Windows, programs usually don't have stderr at all, so show the
397 // messages also under debugger - unless it's a console program
398 #if defined(__WXMSW__) && wxUSE_GUI
399 OutputDebugString(str
+ wxT("\r\n"));
403 // ----------------------------------------------------------------------------
404 // wxLogStream implementation
405 // ----------------------------------------------------------------------------
407 #if wxUSE_STD_IOSTREAM
408 wxLogStream::wxLogStream(ostream
*ostr
)
416 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
418 (*m_ostr
) << wxConvertWX2MB(szString
) << endl
;
420 #endif // wxUSE_STD_IOSTREAM
422 // ============================================================================
423 // Global functions/variables
424 // ============================================================================
426 // ----------------------------------------------------------------------------
428 // ----------------------------------------------------------------------------
430 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
431 bool wxLog::ms_doLog
= TRUE
;
432 bool wxLog::ms_bAutoCreate
= TRUE
;
434 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
436 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
437 wxArrayString
wxLog::ms_aTraceMasks
;
439 // ----------------------------------------------------------------------------
440 // stdout error logging helper
441 // ----------------------------------------------------------------------------
443 // helper function: wraps the message and justifies it under given position
444 // (looks more pretty on the terminal). Also adds newline at the end.
446 // TODO this is now disabled until I find a portable way of determining the
447 // terminal window size (ok, I found it but does anybody really cares?)
448 #ifdef LOG_PRETTY_WRAP
449 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
451 size_t nMax
= 80; // FIXME
452 size_t nStart
= strlen(pszPrefix
);
456 while ( *psz
!= '\0' ) {
457 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
461 if ( *psz
!= '\0' ) {
463 for ( n
= 0; n
< nStart
; n
++ )
466 // as we wrapped, squeeze all white space
467 while ( isspace(*psz
) )
474 #endif //LOG_PRETTY_WRAP
476 // ----------------------------------------------------------------------------
477 // error code/error message retrieval functions
478 // ----------------------------------------------------------------------------
480 // get error code from syste
481 unsigned long wxSysErrorCode()
485 return ::GetLastError();
487 // TODO what to do on Windows 3.1?
495 // get error message from system
496 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
499 nErrCode
= wxSysErrorCode();
503 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
505 // get error message from system
507 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
509 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
513 // copy it to our buffer and free memory
514 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
515 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
518 // returned string is capitalized and ended with '\r\n' - bad
519 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
520 size_t len
= wxStrlen(s_szBuf
);
523 if ( s_szBuf
[len
- 2] == wxT('\r') )
524 s_szBuf
[len
- 2] = wxT('\0');
534 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
535 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
538 return strerror((int)nErrCode
);
543 // ----------------------------------------------------------------------------
545 // ----------------------------------------------------------------------------
549 // break into the debugger
554 #elif defined(__WXMAC__)
560 #elif defined(__UNIX__)
567 // this function is called when an assert fails
568 void wxOnAssert(const wxChar
*szFile
, int nLine
, const wxChar
*szMsg
)
570 // this variable can be set to true to suppress "assert failure" messages
571 static bool s_bNoAsserts
= FALSE
;
572 static bool s_bInAssert
= FALSE
; // FIXME MT-unsafe
575 // He-e-e-e-elp!! we're trapped in endless loop
585 wxChar szBuf
[LOG_BUFFER_SIZE
];
587 // make life easier for people using VC++ IDE: clicking on the message
588 // will take us immediately to the place of the failed assert
589 wxSnprintf(szBuf
, WXSIZEOF(szBuf
),
591 wxT("%s(%d): assert failed"),
593 // make the error message more clear for all the others
594 wxT("Assert failed in file %s at line %d"),
598 if ( szMsg
!= NULL
) {
599 wxStrcat(szBuf
, wxT(": "));
600 wxStrcat(szBuf
, szMsg
);
603 wxStrcat(szBuf
, wxT("."));
606 if ( !s_bNoAsserts
) {
607 // send it to the normal log destination
610 #if wxUSE_GUI || defined(__WXMSW__)
611 // this message is intentionally not translated - it is for
613 wxStrcat(szBuf
, wxT("\nDo you want to stop the program?"
614 "\nYou can also choose [Cancel] to suppress "
615 "further warnings."));
618 switch ( wxMessageBox(szBuf
, "Debug",
619 wxYES_NO
| wxCANCEL
| wxICON_STOP
) ) {
628 //case wxNO: nothing to do
630 #else // !GUI, but MSW
631 switch ( ::MessageBox(NULL
, szBuf
, "Debug",
632 MB_YESNOCANCEL
| MB_ICONSTOP
) ) {
641 //case IDNO: nothing to do