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