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"));
401 #if defined(__WXMAC__) && wxUSE_GUI
402 debugstr(str
+ wxT("\r\n"));
406 // ----------------------------------------------------------------------------
407 // wxLogStream implementation
408 // ----------------------------------------------------------------------------
410 #if wxUSE_STD_IOSTREAM
411 wxLogStream::wxLogStream(ostream
*ostr
)
419 void wxLogStream::DoLogString(const wxChar
*szString
, time_t WXUNUSED(t
))
421 (*m_ostr
) << wxConvertWX2MB(szString
) << endl
;
423 #endif // wxUSE_STD_IOSTREAM
425 // ============================================================================
426 // Global functions/variables
427 // ============================================================================
429 // ----------------------------------------------------------------------------
431 // ----------------------------------------------------------------------------
433 wxLog
*wxLog::ms_pLogger
= (wxLog
*)NULL
;
434 bool wxLog::ms_doLog
= TRUE
;
435 bool wxLog::ms_bAutoCreate
= TRUE
;
438 const wxChar
*wxLog::ms_timestamp
= wxT("%X"); // time only, no date
440 const wxChar
*wxLog::ms_timestamp
= NULL
; // save space
443 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
444 wxArrayString
wxLog::ms_aTraceMasks
;
446 // ----------------------------------------------------------------------------
447 // stdout error logging helper
448 // ----------------------------------------------------------------------------
450 // helper function: wraps the message and justifies it under given position
451 // (looks more pretty on the terminal). Also adds newline at the end.
453 // TODO this is now disabled until I find a portable way of determining the
454 // terminal window size (ok, I found it but does anybody really cares?)
455 #ifdef LOG_PRETTY_WRAP
456 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
458 size_t nMax
= 80; // FIXME
459 size_t nStart
= strlen(pszPrefix
);
463 while ( *psz
!= '\0' ) {
464 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
468 if ( *psz
!= '\0' ) {
470 for ( n
= 0; n
< nStart
; n
++ )
473 // as we wrapped, squeeze all white space
474 while ( isspace(*psz
) )
481 #endif //LOG_PRETTY_WRAP
483 // ----------------------------------------------------------------------------
484 // error code/error message retrieval functions
485 // ----------------------------------------------------------------------------
487 // get error code from syste
488 unsigned long wxSysErrorCode()
492 return ::GetLastError();
494 // TODO what to do on Windows 3.1?
502 // get error message from system
503 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
506 nErrCode
= wxSysErrorCode();
510 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
512 // get error message from system
514 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
516 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
520 // copy it to our buffer and free memory
521 wxStrncpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
522 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = wxT('\0');
525 // returned string is capitalized and ended with '\r\n' - bad
526 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
527 size_t len
= wxStrlen(s_szBuf
);
530 if ( s_szBuf
[len
- 2] == wxT('\r') )
531 s_szBuf
[len
- 2] = wxT('\0');
541 static wxChar s_szBuf
[LOG_BUFFER_SIZE
/ 2];
542 wxConvCurrent
->MB2WC(s_szBuf
, strerror(nErrCode
), WXSIZEOF(s_szBuf
) -1);
545 return strerror((int)nErrCode
);
550 // ----------------------------------------------------------------------------
552 // ----------------------------------------------------------------------------
556 // break into the debugger
561 #elif defined(__WXMAC__)
567 #elif defined(__UNIX__)
574 // this function is called when an assert fails
575 void wxOnAssert(const wxChar
*szFile
, int nLine
, const wxChar
*szMsg
)
577 // this variable can be set to true to suppress "assert failure" messages
578 static bool s_bNoAsserts
= FALSE
;
579 static bool s_bInAssert
= FALSE
; // FIXME MT-unsafe
582 // He-e-e-e-elp!! we're trapped in endless loop
592 wxChar szBuf
[LOG_BUFFER_SIZE
];
594 // make life easier for people using VC++ IDE: clicking on the message
595 // will take us immediately to the place of the failed assert
596 wxSnprintf(szBuf
, WXSIZEOF(szBuf
),
598 wxT("%s(%d): assert failed"),
600 // make the error message more clear for all the others
601 wxT("Assert failed in file %s at line %d"),
605 if ( szMsg
!= NULL
) {
606 wxStrcat(szBuf
, wxT(": "));
607 wxStrcat(szBuf
, szMsg
);
610 wxStrcat(szBuf
, wxT("."));
613 if ( !s_bNoAsserts
) {
614 // send it to the normal log destination
617 #if wxUSE_GUI || defined(__WXMSW__)
618 // this message is intentionally not translated - it is for
620 wxStrcat(szBuf
, wxT("\nDo you want to stop the program?"
621 "\nYou can also choose [Cancel] to suppress "
622 "further warnings."));
625 switch ( wxMessageBox(szBuf
, "Debug",
626 wxYES_NO
| wxCANCEL
| wxICON_STOP
) ) {
635 //case wxNO: nothing to do
637 #else // !GUI, but MSW
638 switch ( ::MessageBox(NULL
, szBuf
, "Debug",
639 MB_YESNOCANCEL
| MB_ICONSTOP
) ) {
648 //case IDNO: nothing to do