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