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