Ensure that component levels map is initialized before it's used (closes #10990).
[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 = ms_pLogger;
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 if ( ms_bAutoCreate && ms_pLogger == NULL ) {
468 // prevent infinite recursion if someone calls wxLogXXX() from
469 // wxApp::CreateLogTarget()
470 static bool s_bInGetActiveTarget = false;
471 if ( !s_bInGetActiveTarget ) {
472 s_bInGetActiveTarget = true;
473
474 // ask the application to create a log target for us
475 if ( wxTheApp != NULL )
476 ms_pLogger = wxTheApp->GetTraits()->CreateLogTarget();
477 else
478 ms_pLogger = new wxLogStderr;
479
480 s_bInGetActiveTarget = false;
481
482 // do nothing if it fails - what can we do?
483 }
484 }
485
486 return ms_pLogger;
487 }
488
489 wxLog *wxLog::SetActiveTarget(wxLog *pLogger)
490 {
491 if ( ms_pLogger != NULL ) {
492 // flush the old messages before changing because otherwise they might
493 // get lost later if this target is not restored
494 ms_pLogger->Flush();
495 }
496
497 wxLog *pOldLogger = ms_pLogger;
498 ms_pLogger = pLogger;
499
500 return pOldLogger;
501 }
502
503 #if wxUSE_THREADS
504 /* static */
505 wxLog *wxLog::SetThreadActiveTarget(wxLog *logger)
506 {
507 wxASSERT_MSG( !wxThread::IsMain(), "use SetActiveTarget() for main thread" );
508
509 wxLog * const oldLogger = wxThreadInfo.logger;
510 if ( oldLogger )
511 oldLogger->Flush();
512
513 wxThreadInfo.logger = logger;
514
515 return oldLogger;
516 }
517 #endif // wxUSE_THREADS
518
519 void wxLog::DontCreateOnDemand()
520 {
521 ms_bAutoCreate = false;
522
523 // this is usually called at the end of the program and we assume that it
524 // is *always* called at the end - so we free memory here to avoid false
525 // memory leak reports from wxWin memory tracking code
526 ClearTraceMasks();
527 }
528
529 void wxLog::DoCreateOnDemand()
530 {
531 ms_bAutoCreate = true;
532 }
533
534 // ----------------------------------------------------------------------------
535 // wxLog components levels
536 // ----------------------------------------------------------------------------
537
538 /* static */
539 void wxLog::SetComponentLevel(const wxString& component, wxLogLevel level)
540 {
541 if ( component.empty() )
542 {
543 SetLogLevel(level);
544 }
545 else
546 {
547 wxCRIT_SECT_LOCKER(lock, GetLevelsCS());
548
549 GetComponentLevels()[component] = level;
550 }
551 }
552
553 /* static */
554 wxLogLevel wxLog::GetComponentLevel(wxString component)
555 {
556 wxCRIT_SECT_LOCKER(lock, GetLevelsCS());
557
558 const wxStringToNumHashMap& componentLevels = GetComponentLevels();
559 while ( !component.empty() )
560 {
561 wxStringToNumHashMap::const_iterator
562 it = componentLevels.find(component);
563 if ( it != componentLevels.end() )
564 return static_cast<wxLogLevel>(it->second);
565
566 component = component.BeforeLast('/');
567 }
568
569 return GetLogLevel();
570 }
571
572 // ----------------------------------------------------------------------------
573 // wxLog trace masks
574 // ----------------------------------------------------------------------------
575
576 void wxLog::AddTraceMask(const wxString& str)
577 {
578 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
579
580 ms_aTraceMasks.push_back(str);
581 }
582
583 void wxLog::RemoveTraceMask(const wxString& str)
584 {
585 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
586
587 int index = ms_aTraceMasks.Index(str);
588 if ( index != wxNOT_FOUND )
589 ms_aTraceMasks.RemoveAt((size_t)index);
590 }
591
592 void wxLog::ClearTraceMasks()
593 {
594 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
595
596 ms_aTraceMasks.Clear();
597 }
598
599 /*static*/ bool wxLog::IsAllowedTraceMask(const wxString& mask)
600 {
601 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
602
603 for ( wxArrayString::iterator it = ms_aTraceMasks.begin(),
604 en = ms_aTraceMasks.end();
605 it != en; ++it )
606 {
607 if ( *it == mask)
608 return true;
609 }
610
611 return false;
612 }
613
614 // ----------------------------------------------------------------------------
615 // wxLog miscellaneous other methods
616 // ----------------------------------------------------------------------------
617
618 void wxLog::TimeStamp(wxString *str)
619 {
620 #if wxUSE_DATETIME
621 if ( !ms_timestamp.empty() )
622 {
623 wxChar buf[256];
624 time_t timeNow;
625 (void)time(&timeNow);
626
627 struct tm tm;
628 wxStrftime(buf, WXSIZEOF(buf),
629 ms_timestamp, wxLocaltime_r(&timeNow, &tm));
630
631 str->Empty();
632 *str << buf << wxS(": ");
633 }
634 #endif // wxUSE_DATETIME
635 }
636
637 #if wxUSE_THREADS
638
639 void wxLog::FlushThreadMessages()
640 {
641 // check if we have queued messages from other threads
642 wxLogRecords bufferedLogRecords;
643
644 {
645 wxCriticalSectionLocker lock(GetBackgroundLogCS());
646 bufferedLogRecords.swap(gs_bufferedLogRecords);
647
648 // release the lock now to not keep it while we are logging the
649 // messages below, allowing background threads to run
650 }
651
652 if ( !bufferedLogRecords.empty() )
653 {
654 for ( wxLogRecords::const_iterator it = bufferedLogRecords.begin();
655 it != bufferedLogRecords.end();
656 ++it )
657 {
658 CallDoLogNow(it->level, it->msg, it->info);
659 }
660 }
661 }
662
663 /* static */
664 bool wxLog::IsThreadLoggingEnabled()
665 {
666 return !wxThreadInfo.loggingDisabled;
667 }
668
669 /* static */
670 bool wxLog::EnableThreadLogging(bool enable)
671 {
672 const bool wasEnabled = !wxThreadInfo.loggingDisabled;
673 wxThreadInfo.loggingDisabled = !enable;
674 return wasEnabled;
675 }
676
677 #endif // wxUSE_THREADS
678
679 void wxLog::Flush()
680 {
681 LogLastRepeatIfNeeded();
682 }
683
684 /* static */
685 void wxLog::FlushActive()
686 {
687 if ( ms_suspendCount )
688 return;
689
690 wxLog * const log = GetActiveTarget();
691 if ( log )
692 {
693 #if wxUSE_THREADS
694 if ( wxThread::IsMain() )
695 log->FlushThreadMessages();
696 #endif // wxUSE_THREADS
697
698 log->Flush();
699 }
700 }
701
702 // ----------------------------------------------------------------------------
703 // wxLogBuffer implementation
704 // ----------------------------------------------------------------------------
705
706 void wxLogBuffer::Flush()
707 {
708 wxLog::Flush();
709
710 if ( !m_str.empty() )
711 {
712 wxMessageOutputBest out;
713 out.Printf(wxS("%s"), m_str.c_str());
714 m_str.clear();
715 }
716 }
717
718 void wxLogBuffer::DoLogTextAtLevel(wxLogLevel level, const wxString& msg)
719 {
720 // don't put debug messages in the buffer, we don't want to show
721 // them to the user in a msg box, log them immediately
722 switch ( level )
723 {
724 case wxLOG_Debug:
725 case wxLOG_Trace:
726 wxLog::DoLogTextAtLevel(level, msg);
727 break;
728
729 default:
730 m_str << msg << wxS("\n");
731 }
732 }
733
734 // ----------------------------------------------------------------------------
735 // wxLogStderr class implementation
736 // ----------------------------------------------------------------------------
737
738 wxLogStderr::wxLogStderr(FILE *fp)
739 {
740 if ( fp == NULL )
741 m_fp = stderr;
742 else
743 m_fp = fp;
744 }
745
746 void wxLogStderr::DoLogText(const wxString& msg)
747 {
748 wxFputs(msg + '\n', m_fp);
749 fflush(m_fp);
750
751 // under GUI systems such as Windows or Mac, programs usually don't have
752 // stderr at all, so show the messages also somewhere else, typically in
753 // the debugger window so that they go at least somewhere instead of being
754 // simply lost
755 if ( m_fp == stderr )
756 {
757 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
758 if ( traits && !traits->HasStderr() )
759 {
760 wxMessageOutputDebug().Output(msg + wxS('\n'));
761 }
762 }
763 }
764
765 // ----------------------------------------------------------------------------
766 // wxLogStream implementation
767 // ----------------------------------------------------------------------------
768
769 #if wxUSE_STD_IOSTREAM
770 #include "wx/ioswrap.h"
771 wxLogStream::wxLogStream(wxSTD ostream *ostr)
772 {
773 if ( ostr == NULL )
774 m_ostr = &wxSTD cerr;
775 else
776 m_ostr = ostr;
777 }
778
779 void wxLogStream::DoLogText(const wxString& msg)
780 {
781 (*m_ostr) << msg << wxSTD endl;
782 }
783 #endif // wxUSE_STD_IOSTREAM
784
785 // ----------------------------------------------------------------------------
786 // wxLogChain
787 // ----------------------------------------------------------------------------
788
789 wxLogChain::wxLogChain(wxLog *logger)
790 {
791 m_bPassMessages = true;
792
793 m_logNew = logger;
794 m_logOld = wxLog::SetActiveTarget(this);
795 }
796
797 wxLogChain::~wxLogChain()
798 {
799 delete m_logOld;
800
801 if ( m_logNew != this )
802 delete m_logNew;
803 }
804
805 void wxLogChain::SetLog(wxLog *logger)
806 {
807 if ( m_logNew != this )
808 delete m_logNew;
809
810 m_logNew = logger;
811 }
812
813 void wxLogChain::Flush()
814 {
815 if ( m_logOld )
816 m_logOld->Flush();
817
818 // be careful to avoid infinite recursion
819 if ( m_logNew && m_logNew != this )
820 m_logNew->Flush();
821 }
822
823 void wxLogChain::DoLogRecord(wxLogLevel level,
824 const wxString& msg,
825 const wxLogRecordInfo& info)
826 {
827 // let the previous logger show it
828 if ( m_logOld && IsPassingMessages() )
829 m_logOld->LogRecord(level, msg, info);
830
831 // and also send it to the new one
832 if ( m_logNew && m_logNew != this )
833 m_logNew->LogRecord(level, msg, info);
834 }
835
836 #ifdef __VISUALC__
837 // "'this' : used in base member initializer list" - so what?
838 #pragma warning(disable:4355)
839 #endif // VC++
840
841 // ----------------------------------------------------------------------------
842 // wxLogInterposer
843 // ----------------------------------------------------------------------------
844
845 wxLogInterposer::wxLogInterposer()
846 : wxLogChain(this)
847 {
848 }
849
850 // ----------------------------------------------------------------------------
851 // wxLogInterposerTemp
852 // ----------------------------------------------------------------------------
853
854 wxLogInterposerTemp::wxLogInterposerTemp()
855 : wxLogChain(this)
856 {
857 DetachOldLog();
858 }
859
860 #ifdef __VISUALC__
861 #pragma warning(default:4355)
862 #endif // VC++
863
864 // ============================================================================
865 // Global functions/variables
866 // ============================================================================
867
868 // ----------------------------------------------------------------------------
869 // static variables
870 // ----------------------------------------------------------------------------
871
872 bool wxLog::ms_bRepetCounting = false;
873
874 wxLog *wxLog::ms_pLogger = NULL;
875 bool wxLog::ms_doLog = true;
876 bool wxLog::ms_bAutoCreate = true;
877 bool wxLog::ms_bVerbose = false;
878
879 wxLogLevel wxLog::ms_logLevel = wxLOG_Max; // log everything by default
880
881 size_t wxLog::ms_suspendCount = 0;
882
883 wxString wxLog::ms_timestamp(wxS("%X")); // time only, no date
884
885 #if WXWIN_COMPATIBILITY_2_8
886 wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
887 #endif // wxDEBUG_LEVEL
888
889 wxArrayString wxLog::ms_aTraceMasks;
890
891 // ----------------------------------------------------------------------------
892 // stdout error logging helper
893 // ----------------------------------------------------------------------------
894
895 // helper function: wraps the message and justifies it under given position
896 // (looks more pretty on the terminal). Also adds newline at the end.
897 //
898 // TODO this is now disabled until I find a portable way of determining the
899 // terminal window size (ok, I found it but does anybody really cares?)
900 #ifdef LOG_PRETTY_WRAP
901 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
902 {
903 size_t nMax = 80; // FIXME
904 size_t nStart = strlen(pszPrefix);
905 fputs(pszPrefix, f);
906
907 size_t n;
908 while ( *psz != '\0' ) {
909 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
910 putc(*psz++, f);
911
912 // wrapped?
913 if ( *psz != '\0' ) {
914 /*putc('\n', f);*/
915 for ( n = 0; n < nStart; n++ )
916 putc(' ', f);
917
918 // as we wrapped, squeeze all white space
919 while ( isspace(*psz) )
920 psz++;
921 }
922 }
923
924 putc('\n', f);
925 }
926 #endif //LOG_PRETTY_WRAP
927
928 // ----------------------------------------------------------------------------
929 // error code/error message retrieval functions
930 // ----------------------------------------------------------------------------
931
932 // get error code from syste
933 unsigned long wxSysErrorCode()
934 {
935 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
936 return ::GetLastError();
937 #else //Unix
938 return errno;
939 #endif //Win/Unix
940 }
941
942 // get error message from system
943 const wxChar *wxSysErrorMsg(unsigned long nErrCode)
944 {
945 if ( nErrCode == 0 )
946 nErrCode = wxSysErrorCode();
947
948 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
949 static wxChar s_szBuf[1024];
950
951 // get error message from system
952 LPVOID lpMsgBuf;
953 if ( ::FormatMessage
954 (
955 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
956 NULL,
957 nErrCode,
958 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
959 (LPTSTR)&lpMsgBuf,
960 0,
961 NULL
962 ) == 0 )
963 {
964 // if this happens, something is seriously wrong, so don't use _() here
965 // for safety
966 wxSprintf(s_szBuf, wxS("unknown error %lx"), nErrCode);
967 return s_szBuf;
968 }
969
970
971 // copy it to our buffer and free memory
972 // Crashes on SmartPhone (FIXME)
973 #if !defined(__SMARTPHONE__) /* of WinCE */
974 if( lpMsgBuf != 0 )
975 {
976 wxStrlcpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf));
977
978 LocalFree(lpMsgBuf);
979
980 // returned string is capitalized and ended with '\r\n' - bad
981 s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
982 size_t len = wxStrlen(s_szBuf);
983 if ( len > 0 ) {
984 // truncate string
985 if ( s_szBuf[len - 2] == wxS('\r') )
986 s_szBuf[len - 2] = wxS('\0');
987 }
988 }
989 else
990 #endif // !__SMARTPHONE__
991 {
992 s_szBuf[0] = wxS('\0');
993 }
994
995 return s_szBuf;
996 #else // !__WXMSW__
997 #if wxUSE_UNICODE
998 static wchar_t s_wzBuf[1024];
999 wxConvCurrent->MB2WC(s_wzBuf, strerror((int)nErrCode),
1000 WXSIZEOF(s_wzBuf) - 1);
1001 return s_wzBuf;
1002 #else
1003 return strerror((int)nErrCode);
1004 #endif
1005 #endif // __WXMSW__/!__WXMSW__
1006 }
1007
1008 #endif // wxUSE_LOG