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