]> git.saurik.com Git - wxWidgets.git/blob - src/common/log.cpp
include "module.h"
[wxWidgets.git] / src / common / log.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: log.cpp
3 // Purpose: Assorted wxLogXXX functions, and wxLog (sink for logs)
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 29/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 #pragma implementation "log.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 // wxWindows
32 #ifndef WX_PRECOMP
33 #include "wx/string.h"
34 #include "wx/intl.h"
35 #include "wx/app.h"
36
37 #if wxUSE_GUI
38 #include "wx/window.h"
39 #ifdef __WXMSW__
40 #include "wx/msw/private.h"
41 #endif
42 #include "wx/msgdlg.h"
43 #endif
44 #endif //WX_PRECOMP
45
46 #include "wx/file.h"
47 #include "wx/textfile.h"
48 #include "wx/utils.h"
49 #include "wx/wxchar.h"
50 #include "wx/log.h"
51 #include "wx/thread.h"
52
53 // other standard headers
54 #include <errno.h>
55 #include <stdlib.h>
56 #include <time.h>
57
58 #ifdef __WXMSW__
59 #include "wx/msw/private.h" // includes windows.h for OutputDebugString
60 #else //Unix
61 #include <signal.h>
62 #endif //Win/Unix
63
64 // ----------------------------------------------------------------------------
65 // non member functions
66 // ----------------------------------------------------------------------------
67
68 // define this to enable wrapping of log messages
69 //#define LOG_PRETTY_WRAP
70
71 #ifdef LOG_PRETTY_WRAP
72 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz);
73 #endif
74
75 // ============================================================================
76 // implementation
77 // ============================================================================
78
79 // ----------------------------------------------------------------------------
80 // globals
81 // ----------------------------------------------------------------------------
82
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)
86
87 // static buffer for error messages
88 static wxChar s_szBuf[LOG_BUFFER_SIZE];
89
90 #if wxUSE_THREADS
91
92 // the critical section protecting the static buffer
93 static wxCriticalSection gs_csLogBuf;
94
95 #endif // wxUSE_THREADS
96
97 // ----------------------------------------------------------------------------
98 // implementation of Log functions
99 //
100 // NB: unfortunately we need all these distinct functions, we can't make them
101 // macros and not all compilers inline vararg functions.
102 // ----------------------------------------------------------------------------
103
104 // generic log function
105 void wxLogGeneric(wxLogLevel level, const wxChar *szFormat, ...)
106 {
107 if ( wxLog::GetActiveTarget() != NULL ) {
108 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
109
110 va_list argptr;
111 va_start(argptr, szFormat);
112 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
113 va_end(argptr);
114
115 wxLog::OnLog(level, s_szBuf, time(NULL));
116 }
117 }
118
119 #define IMPLEMENT_LOG_FUNCTION(level) \
120 void wxLog##level(const wxChar *szFormat, ...) \
121 { \
122 if ( wxLog::GetActiveTarget() != NULL ) { \
123 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
124 \
125 va_list argptr; \
126 va_start(argptr, szFormat); \
127 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
128 va_end(argptr); \
129 \
130 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
131 } \
132 }
133
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)
140
141 // same as info, but only if 'verbose' mode is on
142 void wxLogVerbose(const wxChar *szFormat, ...)
143 {
144 wxLog *pLog = wxLog::GetActiveTarget();
145 if ( pLog != NULL && pLog->GetVerbose() ) {
146 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
147
148 va_list argptr;
149 va_start(argptr, szFormat);
150 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
151 va_end(argptr);
152
153 wxLog::OnLog(wxLOG_Info, s_szBuf, time(NULL));
154 }
155 }
156
157 // debug functions
158 #ifdef __WXDEBUG__
159 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
160 void wxLog##level(const wxChar *szFormat, ...) \
161 { \
162 if ( wxLog::GetActiveTarget() != NULL ) { \
163 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
164 \
165 va_list argptr; \
166 va_start(argptr, szFormat); \
167 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr); \
168 va_end(argptr); \
169 \
170 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
171 } \
172 }
173
174 void wxLogTrace(const wxChar *mask, const wxChar *szFormat, ...)
175 {
176 wxLog *pLog = wxLog::GetActiveTarget();
177
178 if ( pLog != NULL && wxLog::IsAllowedTraceMask(mask) ) {
179 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
180
181 va_list argptr;
182 va_start(argptr, szFormat);
183 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
184 va_end(argptr);
185
186 wxLog::OnLog(wxLOG_Trace, s_szBuf, time(NULL));
187 }
188 }
189
190 void wxLogTrace(wxTraceMask mask, const wxChar *szFormat, ...)
191 {
192 wxLog *pLog = wxLog::GetActiveTarget();
193
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);
199
200 va_list argptr;
201 va_start(argptr, szFormat);
202 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
203 va_end(argptr);
204
205 wxLog::OnLog(wxLOG_Trace, s_szBuf, time(NULL));
206 }
207 }
208
209 #else // release
210 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
211 #endif
212
213 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug)
214 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace)
215
216 // wxLogSysError: one uses the last error code, for other you must give it
217 // explicitly
218
219 // common part of both wxLogSysError
220 void wxLogSysErrorHelper(long lErrCode)
221 {
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));
226
227 wxLog::OnLog(wxLOG_Error, s_szBuf, time(NULL));
228 }
229
230 void WXDLLEXPORT wxLogSysError(const wxChar *szFormat, ...)
231 {
232 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
233
234 va_list argptr;
235 va_start(argptr, szFormat);
236 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
237 va_end(argptr);
238
239 wxLogSysErrorHelper(wxSysErrorCode());
240 }
241
242 void WXDLLEXPORT wxLogSysError(long lErrCode, const wxChar *szFormat, ...)
243 {
244 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
245
246 va_list argptr;
247 va_start(argptr, szFormat);
248 wxVsnprintf(s_szBuf, WXSIZEOF(s_szBuf), szFormat, argptr);
249 va_end(argptr);
250
251 wxLogSysErrorHelper(lErrCode);
252 }
253
254 // ----------------------------------------------------------------------------
255 // wxLog class implementation
256 // ----------------------------------------------------------------------------
257
258 wxLog::wxLog()
259 {
260 m_bHasMessages = FALSE;
261
262 // enable verbose messages by default in the debug builds
263 #ifdef __WXDEBUG__
264 m_bVerbose = TRUE;
265 #else // release
266 m_bVerbose = FALSE;
267 #endif // debug/release
268 }
269
270 wxLog *wxLog::GetActiveTarget()
271 {
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;
278
279 // ask the application to create a log target for us
280 if ( wxTheApp != NULL )
281 ms_pLogger = wxTheApp->CreateLogTarget();
282 else
283 ms_pLogger = new wxLogStderr;
284
285 s_bInGetActiveTarget = FALSE;
286
287 // do nothing if it fails - what can we do?
288 }
289 }
290
291 return ms_pLogger;
292 }
293
294 wxLog *wxLog::SetActiveTarget(wxLog *pLogger)
295 {
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
299 ms_pLogger->Flush();
300 }
301
302 wxLog *pOldLogger = ms_pLogger;
303 ms_pLogger = pLogger;
304
305 return pOldLogger;
306 }
307
308 void wxLog::RemoveTraceMask(const wxString& str)
309 {
310 int index = ms_aTraceMasks.Index(str);
311 if ( index != wxNOT_FOUND )
312 ms_aTraceMasks.Remove((size_t)index);
313 }
314
315 void wxLog::TimeStamp(wxString *str)
316 {
317 if ( ms_timestamp )
318 {
319 wxChar buf[256];
320 time_t timeNow;
321 (void)time(&timeNow);
322 wxStrftime(buf, WXSIZEOF(buf), ms_timestamp, localtime(&timeNow));
323
324 str->Empty();
325 *str << buf << wxT(": ");
326 }
327 }
328
329 void wxLog::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
330 {
331 switch ( level ) {
332 case wxLOG_FatalError:
333 DoLogString(wxString(_("Fatal error: ")) + szString, t);
334 DoLogString(_("Program aborted."), t);
335 Flush();
336 abort();
337 break;
338
339 case wxLOG_Error:
340 DoLogString(wxString(_("Error: ")) + szString, t);
341 break;
342
343 case wxLOG_Warning:
344 DoLogString(wxString(_("Warning: ")) + szString, t);
345 break;
346
347 case wxLOG_Info:
348 if ( GetVerbose() )
349 case wxLOG_Message:
350 case wxLOG_Status:
351 default: // log unknown log levels too
352 DoLogString(szString, t);
353 break;
354
355 case wxLOG_Trace:
356 case wxLOG_Debug:
357 #ifdef __WXDEBUG__
358 DoLogString(szString, t);
359 #endif
360 break;
361 }
362 }
363
364 void wxLog::DoLogString(const wxChar *WXUNUSED(szString), time_t WXUNUSED(t))
365 {
366 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
367 }
368
369 void wxLog::Flush()
370 {
371 // do nothing
372 }
373
374 // ----------------------------------------------------------------------------
375 // wxLogStderr class implementation
376 // ----------------------------------------------------------------------------
377
378 wxLogStderr::wxLogStderr(FILE *fp)
379 {
380 if ( fp == NULL )
381 m_fp = stderr;
382 else
383 m_fp = fp;
384 }
385
386 void wxLogStderr::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
387 {
388 wxString str;
389 TimeStamp(&str);
390 str << szString;
391
392 fputs(str.mb_str(), m_fp);
393 fputc(_T('\n'), m_fp);
394 fflush(m_fp);
395
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"));
400 #endif // MSW
401 }
402
403 // ----------------------------------------------------------------------------
404 // wxLogStream implementation
405 // ----------------------------------------------------------------------------
406
407 #if wxUSE_STD_IOSTREAM
408 wxLogStream::wxLogStream(ostream *ostr)
409 {
410 if ( ostr == NULL )
411 m_ostr = &cerr;
412 else
413 m_ostr = ostr;
414 }
415
416 void wxLogStream::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
417 {
418 (*m_ostr) << wxConvertWX2MB(szString) << endl;
419 }
420 #endif // wxUSE_STD_IOSTREAM
421
422 // ============================================================================
423 // Global functions/variables
424 // ============================================================================
425
426 // ----------------------------------------------------------------------------
427 // static variables
428 // ----------------------------------------------------------------------------
429
430 wxLog *wxLog::ms_pLogger = (wxLog *)NULL;
431 bool wxLog::ms_doLog = TRUE;
432 bool wxLog::ms_bAutoCreate = TRUE;
433
434 #if wxUSE_GUI
435 const wxChar *wxLog::ms_timestamp = wxT("%X"); // time only, no date
436 #else
437 const wxChar *wxLog::ms_timestamp = NULL; // save space
438 #endif
439
440 wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
441 wxArrayString wxLog::ms_aTraceMasks;
442
443 // ----------------------------------------------------------------------------
444 // stdout error logging helper
445 // ----------------------------------------------------------------------------
446
447 // helper function: wraps the message and justifies it under given position
448 // (looks more pretty on the terminal). Also adds newline at the end.
449 //
450 // TODO this is now disabled until I find a portable way of determining the
451 // terminal window size (ok, I found it but does anybody really cares?)
452 #ifdef LOG_PRETTY_WRAP
453 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
454 {
455 size_t nMax = 80; // FIXME
456 size_t nStart = strlen(pszPrefix);
457 fputs(pszPrefix, f);
458
459 size_t n;
460 while ( *psz != '\0' ) {
461 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
462 putc(*psz++, f);
463
464 // wrapped?
465 if ( *psz != '\0' ) {
466 /*putc('\n', f);*/
467 for ( n = 0; n < nStart; n++ )
468 putc(' ', f);
469
470 // as we wrapped, squeeze all white space
471 while ( isspace(*psz) )
472 psz++;
473 }
474 }
475
476 putc('\n', f);
477 }
478 #endif //LOG_PRETTY_WRAP
479
480 // ----------------------------------------------------------------------------
481 // error code/error message retrieval functions
482 // ----------------------------------------------------------------------------
483
484 // get error code from syste
485 unsigned long wxSysErrorCode()
486 {
487 #ifdef __WXMSW__
488 #ifdef __WIN32__
489 return ::GetLastError();
490 #else //WIN16
491 // TODO what to do on Windows 3.1?
492 return 0;
493 #endif //WIN16/32
494 #else //Unix
495 return errno;
496 #endif //Win/Unix
497 }
498
499 // get error message from system
500 const wxChar *wxSysErrorMsg(unsigned long nErrCode)
501 {
502 if ( nErrCode == 0 )
503 nErrCode = wxSysErrorCode();
504
505 #ifdef __WXMSW__
506 #ifdef __WIN32__
507 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
508
509 // get error message from system
510 LPVOID lpMsgBuf;
511 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
512 NULL, nErrCode,
513 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
514 (LPTSTR)&lpMsgBuf,
515 0, NULL);
516
517 // copy it to our buffer and free memory
518 wxStrncpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf) - 1);
519 s_szBuf[WXSIZEOF(s_szBuf) - 1] = wxT('\0');
520 LocalFree(lpMsgBuf);
521
522 // returned string is capitalized and ended with '\r\n' - bad
523 s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
524 size_t len = wxStrlen(s_szBuf);
525 if ( len > 0 ) {
526 // truncate string
527 if ( s_szBuf[len - 2] == wxT('\r') )
528 s_szBuf[len - 2] = wxT('\0');
529 }
530
531 return s_szBuf;
532 #else //Win16
533 // TODO
534 return NULL;
535 #endif // Win16/32
536 #else // Unix
537 #if wxUSE_UNICODE
538 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
539 wxConvCurrent->MB2WC(s_szBuf, strerror(nErrCode), WXSIZEOF(s_szBuf) -1);
540 return s_szBuf;
541 #else
542 return strerror((int)nErrCode);
543 #endif
544 #endif // Win/Unix
545 }
546
547 // ----------------------------------------------------------------------------
548 // debug helper
549 // ----------------------------------------------------------------------------
550
551 #ifdef __WXDEBUG__
552
553 // break into the debugger
554 void Trap()
555 {
556 #ifdef __WXMSW__
557 DebugBreak();
558 #elif defined(__WXMAC__)
559 #if __powerc
560 Debugger();
561 #else
562 SysBreak();
563 #endif
564 #elif defined(__UNIX__)
565 raise(SIGTRAP);
566 #else
567 // TODO
568 #endif // Win/Unix
569 }
570
571 // this function is called when an assert fails
572 void wxOnAssert(const wxChar *szFile, int nLine, const wxChar *szMsg)
573 {
574 // this variable can be set to true to suppress "assert failure" messages
575 static bool s_bNoAsserts = FALSE;
576 static bool s_bInAssert = FALSE; // FIXME MT-unsafe
577
578 if ( s_bInAssert ) {
579 // He-e-e-e-elp!! we're trapped in endless loop
580 Trap();
581
582 s_bInAssert = FALSE;
583
584 return;
585 }
586
587 s_bInAssert = TRUE;
588
589 wxChar szBuf[LOG_BUFFER_SIZE];
590
591 // make life easier for people using VC++ IDE: clicking on the message
592 // will take us immediately to the place of the failed assert
593 wxSnprintf(szBuf, WXSIZEOF(szBuf),
594 #ifdef __VISUALC__
595 wxT("%s(%d): assert failed"),
596 #else // !VC++
597 // make the error message more clear for all the others
598 wxT("Assert failed in file %s at line %d"),
599 #endif // VC/!VC
600 szFile, nLine);
601
602 if ( szMsg != NULL ) {
603 wxStrcat(szBuf, wxT(": "));
604 wxStrcat(szBuf, szMsg);
605 }
606 else {
607 wxStrcat(szBuf, wxT("."));
608 }
609
610 if ( !s_bNoAsserts ) {
611 // send it to the normal log destination
612 wxLogDebug(szBuf);
613
614 #if wxUSE_GUI || defined(__WXMSW__)
615 // this message is intentionally not translated - it is for
616 // developpers only
617 wxStrcat(szBuf, wxT("\nDo you want to stop the program?"
618 "\nYou can also choose [Cancel] to suppress "
619 "further warnings."));
620
621 #if wxUSE_GUI
622 switch ( wxMessageBox(szBuf, "Debug",
623 wxYES_NO | wxCANCEL | wxICON_STOP ) ) {
624 case wxYES:
625 Trap();
626 break;
627
628 case wxCANCEL:
629 s_bNoAsserts = TRUE;
630 break;
631
632 //case wxNO: nothing to do
633 }
634 #else // !GUI, but MSW
635 switch ( ::MessageBox(NULL, szBuf, "Debug",
636 MB_YESNOCANCEL | MB_ICONSTOP ) ) {
637 case IDYES:
638 Trap();
639 break;
640
641 case IDCANCEL:
642 s_bNoAsserts = TRUE;
643 break;
644
645 //case IDNO: nothing to do
646 }
647 #endif // GUI or MSW
648
649 #else // !GUI
650 Trap();
651 #endif // GUI/!GUI
652 }
653
654 s_bInAssert = FALSE;
655 }
656
657 #endif //WXDEBUG
658