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