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