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