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