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