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