add a critical section protecting ms_prev variables (replaces patch 1819224)
[wxWidgets.git] / src / common / log.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/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 licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_LOG
28
29 // wxWidgets
30 #ifndef WX_PRECOMP
31 #include "wx/log.h"
32 #include "wx/app.h"
33 #include "wx/arrstr.h"
34 #include "wx/intl.h"
35 #include "wx/string.h"
36 #include "wx/utils.h"
37 #endif //WX_PRECOMP
38
39 #include "wx/apptrait.h"
40 #include "wx/datetime.h"
41 #include "wx/file.h"
42 #include "wx/msgout.h"
43 #include "wx/textfile.h"
44 #include "wx/thread.h"
45 #include "wx/crt.h"
46
47 // other standard headers
48 #ifndef __WXWINCE__
49 #include <errno.h>
50 #endif
51
52 #include <stdlib.h>
53
54 #ifndef __WXWINCE__
55 #include <time.h>
56 #else
57 #include "wx/msw/wince/time.h"
58 #endif
59
60 #if defined(__WINDOWS__)
61 #include "wx/msw/private.h" // includes windows.h
62 #endif
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 // implementation of Log functions
81 //
82 // NB: unfortunately we need all these distinct functions, we can't make them
83 // macros and not all compilers inline vararg functions.
84 // ----------------------------------------------------------------------------
85
86 // generic log function
87 void wxVLogGeneric(wxLogLevel level, const wxString& format, va_list argptr)
88 {
89 if ( wxLog::IsEnabled() ) {
90 wxLog::OnLog(level, wxString::FormatV(format, argptr), time(NULL));
91 }
92 }
93
94 #if !wxUSE_UTF8_LOCALE_ONLY
95 void wxDoLogGenericWchar(wxLogLevel level, const wxChar *format, ...)
96 {
97 va_list argptr;
98 va_start(argptr, format);
99 wxVLogGeneric(level, format, argptr);
100 va_end(argptr);
101 }
102 #endif // wxUSE_UTF8_LOCALE_ONLY
103
104 #if wxUSE_UNICODE_UTF8
105 void wxDoLogGenericUtf8(wxLogLevel level, const char *format, ...)
106 {
107 va_list argptr;
108 va_start(argptr, format);
109 wxVLogGeneric(level, format, argptr);
110 va_end(argptr);
111 }
112 #endif // wxUSE_UNICODE_UTF8
113
114 #if !wxUSE_UTF8_LOCALE_ONLY
115 #define IMPLEMENT_LOG_FUNCTION_WCHAR(level) \
116 void wxDoLog##level##Wchar(const wxChar *format, ...) \
117 { \
118 va_list argptr; \
119 va_start(argptr, format); \
120 wxVLog##level(format, argptr); \
121 va_end(argptr); \
122 }
123 #else
124 #define IMPLEMENT_LOG_FUNCTION_WCHAR(level)
125 #endif
126
127 #if wxUSE_UNICODE_UTF8
128 #define IMPLEMENT_LOG_FUNCTION_UTF8(level) \
129 void wxDoLog##level##Utf8(const char *format, ...) \
130 { \
131 va_list argptr; \
132 va_start(argptr, format); \
133 wxVLog##level(format, argptr); \
134 va_end(argptr); \
135 }
136 #else
137 #define IMPLEMENT_LOG_FUNCTION_UTF8(level)
138 #endif
139
140 #define IMPLEMENT_LOG_FUNCTION(level) \
141 void wxVLog##level(const wxString& format, va_list argptr) \
142 { \
143 if ( wxLog::IsEnabled() ) { \
144 wxLog::OnLog(wxLOG_##level, \
145 wxString::FormatV(format, argptr), time(NULL)); \
146 } \
147 } \
148 IMPLEMENT_LOG_FUNCTION_WCHAR(level) \
149 IMPLEMENT_LOG_FUNCTION_UTF8(level)
150
151 IMPLEMENT_LOG_FUNCTION(Error)
152 IMPLEMENT_LOG_FUNCTION(Warning)
153 IMPLEMENT_LOG_FUNCTION(Message)
154 IMPLEMENT_LOG_FUNCTION(Info)
155 IMPLEMENT_LOG_FUNCTION(Status)
156
157 void wxSafeShowMessage(const wxString& title, const wxString& text)
158 {
159 #ifdef __WINDOWS__
160 ::MessageBox(NULL, text.wx_str(), title.wx_str(), MB_OK | MB_ICONSTOP);
161 #else
162 wxFprintf(stderr, _T("%s: %s\n"), title.c_str(), text.c_str());
163 fflush(stderr);
164 #endif
165 }
166
167 // fatal errors can't be suppressed nor handled by the custom log target and
168 // always terminate the program
169 void wxVLogFatalError(const wxString& format, va_list argptr)
170 {
171 wxSafeShowMessage(_T("Fatal Error"), wxString::FormatV(format, argptr));
172
173 #ifdef __WXWINCE__
174 ExitThread(3);
175 #else
176 abort();
177 #endif
178 }
179
180 #if !wxUSE_UTF8_LOCALE_ONLY
181 void wxDoLogFatalErrorWchar(const wxChar *format, ...)
182 {
183 va_list argptr;
184 va_start(argptr, format);
185 wxVLogFatalError(format, argptr);
186
187 // some compilers warn about unreachable code and it shouldn't matter
188 // for the others anyhow...
189 //va_end(argptr);
190 }
191 #endif // wxUSE_UTF8_LOCALE_ONLY
192
193 #if wxUSE_UNICODE_UTF8
194 void wxDoLogFatalErrorUtf8(const char *format, ...)
195 {
196 va_list argptr;
197 va_start(argptr, format);
198 wxVLogFatalError(format, argptr);
199
200 // some compilers warn about unreachable code and it shouldn't matter
201 // for the others anyhow...
202 //va_end(argptr);
203 }
204 #endif // wxUSE_UNICODE_UTF8
205
206 // same as info, but only if 'verbose' mode is on
207 void wxVLogVerbose(const wxString& format, va_list argptr)
208 {
209 if ( wxLog::IsEnabled() ) {
210 if ( wxLog::GetActiveTarget() != NULL && wxLog::GetVerbose() ) {
211 wxLog::OnLog(wxLOG_Info,
212 wxString::FormatV(format, argptr), time(NULL));
213 }
214 }
215 }
216
217 #if !wxUSE_UTF8_LOCALE_ONLY
218 void wxDoLogVerboseWchar(const wxChar *format, ...)
219 {
220 va_list argptr;
221 va_start(argptr, format);
222 wxVLogVerbose(format, argptr);
223 va_end(argptr);
224 }
225 #endif // !wxUSE_UTF8_LOCALE_ONLY
226
227 #if wxUSE_UNICODE_UTF8
228 void wxDoLogVerboseUtf8(const char *format, ...)
229 {
230 va_list argptr;
231 va_start(argptr, format);
232 wxVLogVerbose(format, argptr);
233 va_end(argptr);
234 }
235 #endif // wxUSE_UNICODE_UTF8
236
237 // debug functions
238 #ifdef __WXDEBUG__
239
240 #if !wxUSE_UTF8_LOCALE_ONLY
241 #define IMPLEMENT_LOG_DEBUG_FUNCTION_WCHAR(level) \
242 void wxDoLog##level##Wchar(const wxChar *format, ...) \
243 { \
244 va_list argptr; \
245 va_start(argptr, format); \
246 wxVLog##level(format, argptr); \
247 va_end(argptr); \
248 }
249 #else
250 #define IMPLEMENT_LOG_DEBUG_FUNCTION_WCHAR(level)
251 #endif
252
253 #if wxUSE_UNICODE_UTF8
254 #define IMPLEMENT_LOG_DEBUG_FUNCTION_UTF8(level) \
255 void wxDoLog##level##Utf8(const char *format, ...) \
256 { \
257 va_list argptr; \
258 va_start(argptr, format); \
259 wxVLog##level(format, argptr); \
260 va_end(argptr); \
261 }
262 #else
263 #define IMPLEMENT_LOG_DEBUG_FUNCTION_UTF8(level)
264 #endif
265
266 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
267 void wxVLog##level(const wxString& format, va_list argptr) \
268 { \
269 if ( wxLog::IsEnabled() ) { \
270 wxLog::OnLog(wxLOG_##level, \
271 wxString::FormatV(format, argptr), time(NULL)); \
272 } \
273 } \
274 IMPLEMENT_LOG_DEBUG_FUNCTION_WCHAR(level) \
275 IMPLEMENT_LOG_DEBUG_FUNCTION_UTF8(level)
276
277
278 void wxVLogTrace(const wxString& mask, const wxString& format, va_list argptr)
279 {
280 if ( wxLog::IsEnabled() && wxLog::IsAllowedTraceMask(mask) ) {
281 wxString msg;
282 msg << _T("(") << mask << _T(") ") << wxString::FormatV(format, argptr);
283
284 wxLog::OnLog(wxLOG_Trace, msg, time(NULL));
285 }
286 }
287
288 #if !wxUSE_UTF8_LOCALE_ONLY
289 void wxDoLogTraceWchar(const wxString& mask, const wxChar *format, ...)
290 {
291 va_list argptr;
292 va_start(argptr, format);
293 wxVLogTrace(mask, format, argptr);
294 va_end(argptr);
295 }
296 #endif // !wxUSE_UTF8_LOCALE_ONLY
297
298 #if wxUSE_UNICODE_UTF8
299 void wxDoLogTraceUtf8(const wxString& mask, const char *format, ...)
300 {
301 va_list argptr;
302 va_start(argptr, format);
303 wxVLogTrace(mask, format, argptr);
304 va_end(argptr);
305 }
306 #endif // wxUSE_UNICODE_UTF8
307
308 void wxVLogTrace(wxTraceMask mask, const wxString& format, va_list argptr)
309 {
310 // we check that all of mask bits are set in the current mask, so
311 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
312 // if both bits are set.
313 if ( wxLog::IsEnabled() && ((wxLog::GetTraceMask() & mask) == mask) ) {
314 wxLog::OnLog(wxLOG_Trace, wxString::FormatV(format, argptr), time(NULL));
315 }
316 }
317
318 #if !wxUSE_UTF8_LOCALE_ONLY
319 void wxDoLogTraceWchar(wxTraceMask mask, const wxChar *format, ...)
320 {
321 va_list argptr;
322 va_start(argptr, format);
323 wxVLogTrace(mask, format, argptr);
324 va_end(argptr);
325 }
326 #endif // !wxUSE_UTF8_LOCALE_ONLY
327
328 #if wxUSE_UNICODE_UTF8
329 void wxDoLogTraceUtf8(wxTraceMask mask, const char *format, ...)
330 {
331 va_list argptr;
332 va_start(argptr, format);
333 wxVLogTrace(mask, format, argptr);
334 va_end(argptr);
335 }
336 #endif // wxUSE_UNICODE_UTF8
337
338 #ifdef __WATCOMC__
339 // workaround for http://bugzilla.openwatcom.org/show_bug.cgi?id=351
340 void wxDoLogTraceWchar(int mask, const wxChar *format, ...)
341 {
342 va_list argptr;
343 va_start(argptr, format);
344 wxVLogTrace(mask, format, argptr);
345 va_end(argptr);
346 }
347
348 void wxDoLogTraceWchar(const char *mask, const wxChar *format, ...)
349 {
350 va_list argptr;
351 va_start(argptr, format);
352 wxVLogTrace(mask, format, argptr);
353 va_end(argptr);
354 }
355
356 void wxDoLogTraceWchar(const wchar_t *mask, const wxChar *format, ...)
357 {
358 va_list argptr;
359 va_start(argptr, format);
360 wxVLogTrace(mask, format, argptr);
361 va_end(argptr);
362 }
363
364 void wxVLogTrace(int mask, const wxString& format, va_list argptr)
365 { wxVLogTrace((wxTraceMask)mask, format, argptr); }
366 void wxVLogTrace(const char *mask, const wxString& format, va_list argptr)
367 { wxVLogTrace(wxString(mask), format, argptr); }
368 void wxVLogTrace(const wchar_t *mask, const wxString& format, va_list argptr)
369 { wxVLogTrace(wxString(mask), format, argptr); }
370 #endif // __WATCOMC__
371
372 #else // release
373 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
374 #endif
375
376 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug)
377 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace)
378
379 // wxLogSysError: one uses the last error code, for other you must give it
380 // explicitly
381
382 // return the system error message description
383 static inline wxString wxLogSysErrorHelper(long err)
384 {
385 return wxString::Format(_(" (error %ld: %s)"), err, wxSysErrorMsg(err));
386 }
387
388 void WXDLLEXPORT wxVLogSysError(const wxString& format, va_list argptr)
389 {
390 wxVLogSysError(wxSysErrorCode(), format, argptr);
391 }
392
393 #if !wxUSE_UTF8_LOCALE_ONLY
394 void WXDLLEXPORT wxDoLogSysErrorWchar(const wxChar *format, ...)
395 {
396 va_list argptr;
397 va_start(argptr, format);
398 wxVLogSysError(format, argptr);
399 va_end(argptr);
400 }
401 #endif // !wxUSE_UTF8_LOCALE_ONLY
402
403 #if wxUSE_UNICODE_UTF8
404 void WXDLLEXPORT wxDoLogSysErrorUtf8(const char *format, ...)
405 {
406 va_list argptr;
407 va_start(argptr, format);
408 wxVLogSysError(format, argptr);
409 va_end(argptr);
410 }
411 #endif // wxUSE_UNICODE_UTF8
412
413 void WXDLLEXPORT wxVLogSysError(long err, const wxString& format, va_list argptr)
414 {
415 if ( wxLog::IsEnabled() ) {
416 wxLog::OnLog(wxLOG_Error,
417 wxString::FormatV(format, argptr) + wxLogSysErrorHelper(err),
418 time(NULL));
419 }
420 }
421
422 #if !wxUSE_UTF8_LOCALE_ONLY
423 void WXDLLEXPORT wxDoLogSysErrorWchar(long lErrCode, const wxChar *format, ...)
424 {
425 va_list argptr;
426 va_start(argptr, format);
427 wxVLogSysError(lErrCode, format, argptr);
428 va_end(argptr);
429 }
430 #endif // !wxUSE_UTF8_LOCALE_ONLY
431
432 #if wxUSE_UNICODE_UTF8
433 void WXDLLEXPORT wxDoLogSysErrorUtf8(long lErrCode, const char *format, ...)
434 {
435 va_list argptr;
436 va_start(argptr, format);
437 wxVLogSysError(lErrCode, format, argptr);
438 va_end(argptr);
439 }
440 #endif // wxUSE_UNICODE_UTF8
441
442 #ifdef __WATCOMC__
443 // workaround for http://bugzilla.openwatcom.org/show_bug.cgi?id=351
444 void WXDLLEXPORT wxDoLogSysErrorWchar(unsigned long lErrCode, const wxChar *format, ...)
445 {
446 va_list argptr;
447 va_start(argptr, format);
448 wxVLogSysError(lErrCode, format, argptr);
449 va_end(argptr);
450 }
451
452 void WXDLLEXPORT wxVLogSysError(unsigned long err, const wxString& format, va_list argptr)
453 { wxVLogSysError((long)err, format, argptr); }
454 #endif // __WATCOMC__
455
456 // ----------------------------------------------------------------------------
457 // wxLog class implementation
458 // ----------------------------------------------------------------------------
459
460 /* static */
461 void wxLog::LogLastRepetitionCountIfNeeded()
462 {
463 wxCRIT_SECT_LOCKER(lock, ms_prevCS);
464
465 wxLog *pLogger = GetActiveTarget();
466 if ( pLogger && ms_prevCounter )
467 {
468 wxString msg;
469 #if wxUSE_INTL
470 msg.Printf(wxPLURAL("The previous message repeated once.",
471 "The previous message repeated %lu times.",
472 ms_prevCounter),
473 ms_prevCounter);
474 #else
475 msg.Printf(wxT("The previous message was repeated %lu times."),
476 ms_prevCounter);
477 #endif
478 ms_prevCounter = 0;
479 ms_prevString.clear();
480 pLogger->DoLog(ms_prevLevel, msg, ms_prevTimeStamp);
481 }
482 }
483
484 wxLog::~wxLog()
485 {
486 LogLastRepetitionCountIfNeeded();
487 }
488
489 /* static */
490 void wxLog::OnLog(wxLogLevel level, const wxString& szString, time_t t)
491 {
492 if ( IsEnabled() && ms_logLevel >= level )
493 {
494 wxLog *pLogger = GetActiveTarget();
495 if ( pLogger )
496 {
497 if ( GetRepetitionCounting() )
498 {
499 wxCRIT_SECT_LOCKER(lock, ms_prevCS);
500
501 if ( szString == ms_prevString )
502 {
503 ms_prevCounter++;
504
505 // nothing else to do, in particular, don't log the
506 // repeated message
507 return;
508 }
509
510 LogLastRepetitionCountIfNeeded();
511
512 // reset repetition counter for a new message
513 ms_prevString = szString;
514 ms_prevLevel = level;
515 ms_prevTimeStamp = t;
516 }
517
518 pLogger->DoLog(level, szString, t);
519 }
520 }
521 }
522
523 // deprecated function
524 #if WXWIN_COMPATIBILITY_2_6
525
526 wxChar *wxLog::SetLogBuffer(wxChar * WXUNUSED(buf), size_t WXUNUSED(size))
527 {
528 return NULL;
529 }
530
531 #endif // WXWIN_COMPATIBILITY_2_6
532
533 #if WXWIN_COMPATIBILITY_2_8
534
535 void wxLog::DoLog(wxLogLevel WXUNUSED(level),
536 const char *WXUNUSED(szString),
537 time_t WXUNUSED(t))
538 {
539 }
540
541 void wxLog::DoLog(wxLogLevel WXUNUSED(level),
542 const wchar_t *WXUNUSED(wzString),
543 time_t WXUNUSED(t))
544 {
545 }
546
547 #endif // WXWIN_COMPATIBILITY_2_8
548
549 wxLog *wxLog::GetActiveTarget()
550 {
551 if ( ms_bAutoCreate && ms_pLogger == NULL ) {
552 // prevent infinite recursion if someone calls wxLogXXX() from
553 // wxApp::CreateLogTarget()
554 static bool s_bInGetActiveTarget = false;
555 if ( !s_bInGetActiveTarget ) {
556 s_bInGetActiveTarget = true;
557
558 // ask the application to create a log target for us
559 if ( wxTheApp != NULL )
560 ms_pLogger = wxTheApp->GetTraits()->CreateLogTarget();
561 else
562 ms_pLogger = new wxLogStderr;
563
564 s_bInGetActiveTarget = false;
565
566 // do nothing if it fails - what can we do?
567 }
568 }
569
570 return ms_pLogger;
571 }
572
573 wxLog *wxLog::SetActiveTarget(wxLog *pLogger)
574 {
575 if ( ms_pLogger != NULL ) {
576 // flush the old messages before changing because otherwise they might
577 // get lost later if this target is not restored
578 ms_pLogger->Flush();
579 }
580
581 wxLog *pOldLogger = ms_pLogger;
582 ms_pLogger = pLogger;
583
584 return pOldLogger;
585 }
586
587 void wxLog::DontCreateOnDemand()
588 {
589 ms_bAutoCreate = false;
590
591 // this is usually called at the end of the program and we assume that it
592 // is *always* called at the end - so we free memory here to avoid false
593 // memory leak reports from wxWin memory tracking code
594 ClearTraceMasks();
595 }
596
597 void wxLog::DoCreateOnDemand()
598 {
599 ms_bAutoCreate = true;
600 }
601
602 void wxLog::RemoveTraceMask(const wxString& str)
603 {
604 int index = ms_aTraceMasks.Index(str);
605 if ( index != wxNOT_FOUND )
606 ms_aTraceMasks.RemoveAt((size_t)index);
607 }
608
609 void wxLog::ClearTraceMasks()
610 {
611 ms_aTraceMasks.Clear();
612 }
613
614 void wxLog::TimeStamp(wxString *str)
615 {
616 #if wxUSE_DATETIME
617 if ( !ms_timestamp.empty() )
618 {
619 wxChar buf[256];
620 time_t timeNow;
621 (void)time(&timeNow);
622
623 struct tm tm;
624 wxStrftime(buf, WXSIZEOF(buf),
625 ms_timestamp, wxLocaltime_r(&timeNow, &tm));
626
627 str->Empty();
628 *str << buf << wxT(": ");
629 }
630 #endif // wxUSE_DATETIME
631 }
632
633 void wxLog::DoLog(wxLogLevel level, const wxString& szString, time_t t)
634 {
635 #if WXWIN_COMPATIBILITY_2_8
636 // DoLog() signature changed since 2.8, so we call the old versions here
637 // so that existing custom log classes still work:
638 DoLog(level, (const char*)szString.mb_str(), t);
639 DoLog(level, (const wchar_t*)szString.wc_str(), t);
640 #endif
641
642 switch ( level ) {
643 case wxLOG_FatalError:
644 LogString(_("Fatal error: ") + szString, t);
645 LogString(_("Program aborted."), t);
646 Flush();
647 #ifdef __WXWINCE__
648 ExitThread(3);
649 #else
650 abort();
651 #endif
652 break;
653
654 case wxLOG_Error:
655 LogString(_("Error: ") + szString, t);
656 break;
657
658 case wxLOG_Warning:
659 LogString(_("Warning: ") + szString, t);
660 break;
661
662 case wxLOG_Info:
663 if ( GetVerbose() )
664 case wxLOG_Message:
665 case wxLOG_Status:
666 default: // log unknown log levels too
667 LogString(szString, t);
668 break;
669
670 case wxLOG_Trace:
671 case wxLOG_Debug:
672 #ifdef __WXDEBUG__
673 {
674 wxString msg = level == wxLOG_Trace ? wxT("Trace: ")
675 : wxT("Debug: ");
676 msg << szString;
677 LogString(msg, t);
678 }
679 #endif // Debug
680 break;
681 }
682 }
683
684 void wxLog::DoLogString(const wxString& szString, time_t t)
685 {
686 #if WXWIN_COMPATIBILITY_2_8
687 // DoLogString() signature changed since 2.8, so we call the old versions
688 // here so that existing custom log classes still work; unfortunately this
689 // also means that we can't have the wxFAIL_MSG below in compat mode
690 DoLogString((const char*)szString.mb_str(), t);
691 DoLogString((const wchar_t*)szString.wc_str(), t);
692 #else
693 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
694 wxUnusedVar(szString);
695 wxUnusedVar(t);
696 #endif
697 }
698
699 void wxLog::Flush()
700 {
701 // nothing to do here
702 }
703
704 /*static*/ bool wxLog::IsAllowedTraceMask(const wxString& mask)
705 {
706 for ( wxArrayString::iterator it = ms_aTraceMasks.begin(),
707 en = ms_aTraceMasks.end();
708 it != en; ++it )
709 if ( *it == mask)
710 return true;
711 return false;
712 }
713
714 // ----------------------------------------------------------------------------
715 // wxLogBuffer implementation
716 // ----------------------------------------------------------------------------
717
718 void wxLogBuffer::Flush()
719 {
720 if ( !m_str.empty() )
721 {
722 wxMessageOutputBest out;
723 out.Printf(_T("%s"), m_str.c_str());
724 m_str.clear();
725 }
726 }
727
728 void wxLogBuffer::DoLog(wxLogLevel level, const wxString& szString, time_t t)
729 {
730 switch ( level )
731 {
732 case wxLOG_Trace:
733 case wxLOG_Debug:
734 #ifdef __WXDEBUG__
735 // don't put debug messages in the buffer, we don't want to show
736 // them to the user in a msg box, log them immediately
737 {
738 wxString str;
739 TimeStamp(&str);
740 str += szString;
741
742 wxMessageOutputDebug dbgout;
743 dbgout.Printf(_T("%s\n"), str.c_str());
744 }
745 #endif // __WXDEBUG__
746 break;
747
748 default:
749 wxLog::DoLog(level, szString, t);
750 }
751 }
752
753 void wxLogBuffer::DoLogString(const wxString& szString, time_t WXUNUSED(t))
754 {
755 m_str << szString << _T("\n");
756 }
757
758 // ----------------------------------------------------------------------------
759 // wxLogStderr class implementation
760 // ----------------------------------------------------------------------------
761
762 wxLogStderr::wxLogStderr(FILE *fp)
763 {
764 if ( fp == NULL )
765 m_fp = stderr;
766 else
767 m_fp = fp;
768 }
769
770 void wxLogStderr::DoLogString(const wxString& szString, time_t WXUNUSED(t))
771 {
772 wxString str;
773 TimeStamp(&str);
774 str << szString;
775
776 wxFputs(str, m_fp);
777 wxFputc(_T('\n'), m_fp);
778 fflush(m_fp);
779
780 // under GUI systems such as Windows or Mac, programs usually don't have
781 // stderr at all, so show the messages also somewhere else, typically in
782 // the debugger window so that they go at least somewhere instead of being
783 // simply lost
784 if ( m_fp == stderr )
785 {
786 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
787 if ( traits && !traits->HasStderr() )
788 {
789 wxMessageOutputDebug dbgout;
790 dbgout.Printf(_T("%s\n"), str.c_str());
791 }
792 }
793 }
794
795 // ----------------------------------------------------------------------------
796 // wxLogStream implementation
797 // ----------------------------------------------------------------------------
798
799 #if wxUSE_STD_IOSTREAM
800 #include "wx/ioswrap.h"
801 wxLogStream::wxLogStream(wxSTD ostream *ostr)
802 {
803 if ( ostr == NULL )
804 m_ostr = &wxSTD cerr;
805 else
806 m_ostr = ostr;
807 }
808
809 void wxLogStream::DoLogString(const wxString& szString, time_t WXUNUSED(t))
810 {
811 wxString stamp;
812 TimeStamp(&stamp);
813 (*m_ostr) << stamp << szString << wxSTD endl;
814 }
815 #endif // wxUSE_STD_IOSTREAM
816
817 // ----------------------------------------------------------------------------
818 // wxLogChain
819 // ----------------------------------------------------------------------------
820
821 wxLogChain::wxLogChain(wxLog *logger)
822 {
823 m_bPassMessages = true;
824
825 m_logNew = logger;
826 m_logOld = wxLog::SetActiveTarget(this);
827 }
828
829 wxLogChain::~wxLogChain()
830 {
831 delete m_logOld;
832
833 if ( m_logNew != this )
834 delete m_logNew;
835 }
836
837 void wxLogChain::SetLog(wxLog *logger)
838 {
839 if ( m_logNew != this )
840 delete m_logNew;
841
842 m_logNew = logger;
843 }
844
845 void wxLogChain::Flush()
846 {
847 if ( m_logOld )
848 m_logOld->Flush();
849
850 // be careful to avoid infinite recursion
851 if ( m_logNew && m_logNew != this )
852 m_logNew->Flush();
853 }
854
855 void wxLogChain::DoLog(wxLogLevel level, const wxString& szString, time_t t)
856 {
857 // let the previous logger show it
858 if ( m_logOld && IsPassingMessages() )
859 {
860 // bogus cast just to access protected DoLog
861 ((wxLogChain *)m_logOld)->DoLog(level, szString, t);
862 }
863
864 if ( m_logNew && m_logNew != this )
865 {
866 // as above...
867 ((wxLogChain *)m_logNew)->DoLog(level, szString, t);
868 }
869 }
870
871 #ifdef __VISUALC__
872 // "'this' : used in base member initializer list" - so what?
873 #pragma warning(disable:4355)
874 #endif // VC++
875
876 // ----------------------------------------------------------------------------
877 // wxLogInterposer
878 // ----------------------------------------------------------------------------
879
880 wxLogInterposer::wxLogInterposer()
881 : wxLogChain(this)
882 {
883 }
884
885 // ----------------------------------------------------------------------------
886 // wxLogInterposerTemp
887 // ----------------------------------------------------------------------------
888
889 wxLogInterposerTemp::wxLogInterposerTemp()
890 : wxLogChain(this)
891 {
892 DetachOldLog();
893 }
894
895 #ifdef __VISUALC__
896 #pragma warning(default:4355)
897 #endif // VC++
898
899 // ============================================================================
900 // Global functions/variables
901 // ============================================================================
902
903 // ----------------------------------------------------------------------------
904 // static variables
905 // ----------------------------------------------------------------------------
906
907 bool wxLog::ms_bRepetCounting = false;
908 wxString wxLog::ms_prevString;
909 unsigned int wxLog::ms_prevCounter = 0;
910 time_t wxLog::ms_prevTimeStamp= 0;
911 wxLogLevel wxLog::ms_prevLevel;
912
913 wxLog *wxLog::ms_pLogger = (wxLog *)NULL;
914 bool wxLog::ms_doLog = true;
915 bool wxLog::ms_bAutoCreate = true;
916 bool wxLog::ms_bVerbose = false;
917
918 wxLogLevel wxLog::ms_logLevel = wxLOG_Max; // log everything by default
919
920 size_t wxLog::ms_suspendCount = 0;
921
922 wxString wxLog::ms_timestamp(wxT("%X")); // time only, no date
923
924 wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
925 wxArrayString wxLog::ms_aTraceMasks;
926
927 // ----------------------------------------------------------------------------
928 // stdout error logging helper
929 // ----------------------------------------------------------------------------
930
931 // helper function: wraps the message and justifies it under given position
932 // (looks more pretty on the terminal). Also adds newline at the end.
933 //
934 // TODO this is now disabled until I find a portable way of determining the
935 // terminal window size (ok, I found it but does anybody really cares?)
936 #ifdef LOG_PRETTY_WRAP
937 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
938 {
939 size_t nMax = 80; // FIXME
940 size_t nStart = strlen(pszPrefix);
941 fputs(pszPrefix, f);
942
943 size_t n;
944 while ( *psz != '\0' ) {
945 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
946 putc(*psz++, f);
947
948 // wrapped?
949 if ( *psz != '\0' ) {
950 /*putc('\n', f);*/
951 for ( n = 0; n < nStart; n++ )
952 putc(' ', f);
953
954 // as we wrapped, squeeze all white space
955 while ( isspace(*psz) )
956 psz++;
957 }
958 }
959
960 putc('\n', f);
961 }
962 #endif //LOG_PRETTY_WRAP
963
964 // ----------------------------------------------------------------------------
965 // error code/error message retrieval functions
966 // ----------------------------------------------------------------------------
967
968 // get error code from syste
969 unsigned long wxSysErrorCode()
970 {
971 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
972 return ::GetLastError();
973 #else //Unix
974 return errno;
975 #endif //Win/Unix
976 }
977
978 // get error message from system
979 const wxChar *wxSysErrorMsg(unsigned long nErrCode)
980 {
981 if ( nErrCode == 0 )
982 nErrCode = wxSysErrorCode();
983
984 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
985 static wxChar s_szBuf[1024];
986
987 // get error message from system
988 LPVOID lpMsgBuf;
989 if ( ::FormatMessage
990 (
991 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
992 NULL,
993 nErrCode,
994 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
995 (LPTSTR)&lpMsgBuf,
996 0,
997 NULL
998 ) == 0 )
999 {
1000 // if this happens, something is seriously wrong, so don't use _() here
1001 // for safety
1002 wxSprintf(s_szBuf, _T("unknown error %lx"), nErrCode);
1003 return s_szBuf;
1004 }
1005
1006
1007 // copy it to our buffer and free memory
1008 // Crashes on SmartPhone (FIXME)
1009 #if !defined(__SMARTPHONE__) /* of WinCE */
1010 if( lpMsgBuf != 0 )
1011 {
1012 wxStrncpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf) - 1);
1013 s_szBuf[WXSIZEOF(s_szBuf) - 1] = wxT('\0');
1014
1015 LocalFree(lpMsgBuf);
1016
1017 // returned string is capitalized and ended with '\r\n' - bad
1018 s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
1019 size_t len = wxStrlen(s_szBuf);
1020 if ( len > 0 ) {
1021 // truncate string
1022 if ( s_szBuf[len - 2] == wxT('\r') )
1023 s_szBuf[len - 2] = wxT('\0');
1024 }
1025 }
1026 else
1027 #endif // !__SMARTPHONE__
1028 {
1029 s_szBuf[0] = wxT('\0');
1030 }
1031
1032 return s_szBuf;
1033 #else // !__WXMSW__
1034 #if wxUSE_UNICODE
1035 static wchar_t s_wzBuf[1024];
1036 wxConvCurrent->MB2WC(s_wzBuf, strerror((int)nErrCode),
1037 WXSIZEOF(s_wzBuf) - 1);
1038 return s_wzBuf;
1039 #else
1040 return strerror((int)nErrCode);
1041 #endif
1042 #endif // __WXMSW__/!__WXMSW__
1043 }
1044
1045 #endif // wxUSE_LOG