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