]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/log.cpp
Suppress harmless clang 3.3 warning about unused wxMessageOutputBest field.
[wxWidgets.git] / src / common / log.cpp
... / ...
CommitLineData
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
67const 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
91wxTLS_TYPE(wxThreadSpecificInfo) wxThreadInfoVar;
92
93namespace
94{
95
96// contains messages logged by the other threads and waiting to be shown until
97// Flush() is called in the main one
98typedef wxVector<wxLogRecord> wxLogRecords;
99wxLogRecords 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
105WX_DEFINE_LOG_CS(BackgroundLog);
106
107// this one is used for protecting TraceMasks() from concurrent access
108WX_DEFINE_LOG_CS(TraceMask);
109
110// and this one is used for GetComponentLevels()
111WX_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
132namespace
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
137struct 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
158PreviousLogInfo 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
164WX_DEFINE_GLOBAL_VAR(wxStringToNumHashMap, ComponentLevels);
165
166// ----------------------------------------------------------------------------
167// wxLogOutputBest: wxLog wrapper around wxMessageOutputBest
168// ----------------------------------------------------------------------------
169
170class wxLogOutputBest : public wxLog
171{
172public:
173 wxLogOutputBest() { }
174
175protected:
176 virtual void DoLogText(const wxString& msg)
177 {
178 wxMessageOutputBest().Output(msg);
179 }
180
181private:
182 wxDECLARE_NO_COPY_CLASS(wxLogOutputBest);
183};
184
185} // anonymous namespace
186
187// ============================================================================
188// implementation
189// ============================================================================
190
191// ----------------------------------------------------------------------------
192// helper global functions
193// ----------------------------------------------------------------------------
194
195void 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
209wxString
210wxLogFormatter::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
251wxString
252wxLogFormatter::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
265unsigned 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
301wxLog::~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 */
332void
333wxLog::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 */
345void
346wxLog::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
397void
398wxLog::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
442void 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
463void 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
478void 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
489void wxLog::DoLog(wxLogLevel WXUNUSED(level), const char *szString, time_t t)
490{
491 DoLogString(szString, t);
492}
493
494void 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
505wxLog *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 */
524wxLog *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
548wxLog *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 */
564wxLog *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
578void 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
588void wxLog::DoCreateOnDemand()
589{
590 ms_bAutoCreate = true;
591}
592
593// ----------------------------------------------------------------------------
594// wxLog components levels
595// ----------------------------------------------------------------------------
596
597/* static */
598void 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 */
613wxLogLevel 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
635namespace
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
646wxArrayString& 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
664void wxLog::AddTraceMask(const wxString& str)
665{
666 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
667
668 TraceMasks().push_back(str);
669}
670
671void 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
680void 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
710void wxLog::TimeStamp(wxString *str)
711{
712 if ( !ms_timestamp.empty() )
713 {
714 *str = wxDateTime::UNow().Format(ms_timestamp);
715 *str += wxS(": ");
716 }
717}
718
719void 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
730void wxLog::TimeStamp(wxString*)
731{
732}
733
734void wxLog::TimeStamp(wxString*, time_t)
735{
736}
737
738#endif // wxUSE_DATETIME/!wxUSE_DATETIME
739
740#if wxUSE_THREADS
741
742void 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 */
767bool wxLog::IsThreadLoggingEnabled()
768{
769 return !wxThreadInfo.loggingDisabled;
770}
771
772/* static */
773bool 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
782wxLogFormatter *wxLog::SetFormatter(wxLogFormatter* formatter)
783{
784 wxLogFormatter* formatterOld = m_formatter;
785 m_formatter = formatter ? formatter : new wxLogFormatter;
786
787 return formatterOld;
788}
789
790void wxLog::Flush()
791{
792 LogLastRepeatIfNeeded();
793}
794
795/* static */
796void 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
817void 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
829void 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
849wxLogStderr::wxLogStderr(FILE *fp)
850{
851 if ( fp == NULL )
852 m_fp = stderr;
853 else
854 m_fp = fp;
855}
856
857void wxLogStderr::DoLogText(const wxString& msg)
858{
859 // First send it to stderr, even if we don't have it (e.g. in a Windows GUI
860 // application under) it's not a problem to try to use it and it's easier
861 // than determining whether we do have it or not.
862 wxMessageOutputStderr(m_fp).Output(msg);
863
864 // under GUI systems such as Windows or Mac, programs usually don't have
865 // stderr at all, so show the messages also somewhere else, typically in
866 // the debugger window so that they go at least somewhere instead of being
867 // simply lost
868 if ( m_fp == stderr )
869 {
870 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
871 if ( traits && !traits->HasStderr() )
872 {
873 wxMessageOutputDebug().Output(msg + wxS('\n'));
874 }
875 }
876}
877
878// ----------------------------------------------------------------------------
879// wxLogStream implementation
880// ----------------------------------------------------------------------------
881
882#if wxUSE_STD_IOSTREAM
883#include "wx/ioswrap.h"
884wxLogStream::wxLogStream(wxSTD ostream *ostr)
885{
886 if ( ostr == NULL )
887 m_ostr = &wxSTD cerr;
888 else
889 m_ostr = ostr;
890}
891
892void wxLogStream::DoLogText(const wxString& msg)
893{
894 (*m_ostr) << msg << wxSTD endl;
895}
896#endif // wxUSE_STD_IOSTREAM
897
898// ----------------------------------------------------------------------------
899// wxLogChain
900// ----------------------------------------------------------------------------
901
902wxLogChain::wxLogChain(wxLog *logger)
903{
904 m_bPassMessages = true;
905
906 m_logNew = logger;
907
908 // Notice that we use GetActiveTarget() here instead of directly calling
909 // SetActiveTarget() to trigger wxLog auto-creation: if we're created as
910 // the first logger, we should still chain with the standard, implicit and
911 // possibly still not created standard logger instead of disabling normal
912 // logging entirely.
913 m_logOld = wxLog::GetActiveTarget();
914 wxLog::SetActiveTarget(this);
915}
916
917wxLogChain::~wxLogChain()
918{
919 wxLog::SetActiveTarget(m_logOld);
920
921 if ( m_logNew != this )
922 delete m_logNew;
923}
924
925void wxLogChain::SetLog(wxLog *logger)
926{
927 if ( m_logNew != this )
928 delete m_logNew;
929
930 m_logNew = logger;
931}
932
933void wxLogChain::Flush()
934{
935 if ( m_logOld )
936 m_logOld->Flush();
937
938 // be careful to avoid infinite recursion
939 if ( m_logNew && m_logNew != this )
940 m_logNew->Flush();
941}
942
943void wxLogChain::DoLogRecord(wxLogLevel level,
944 const wxString& msg,
945 const wxLogRecordInfo& info)
946{
947 // let the previous logger show it
948 if ( m_logOld && IsPassingMessages() )
949 m_logOld->LogRecord(level, msg, info);
950
951 // and also send it to the new one
952 if ( m_logNew )
953 {
954 // don't call m_logNew->LogRecord() to avoid infinite recursion when
955 // m_logNew is this object itself
956 if ( m_logNew != this )
957 m_logNew->LogRecord(level, msg, info);
958 else
959 wxLog::DoLogRecord(level, msg, info);
960 }
961}
962
963#ifdef __VISUALC__
964 // "'this' : used in base member initializer list" - so what?
965 #pragma warning(disable:4355)
966#endif // VC++
967
968// ----------------------------------------------------------------------------
969// wxLogInterposer
970// ----------------------------------------------------------------------------
971
972wxLogInterposer::wxLogInterposer()
973 : wxLogChain(this)
974{
975}
976
977// ----------------------------------------------------------------------------
978// wxLogInterposerTemp
979// ----------------------------------------------------------------------------
980
981wxLogInterposerTemp::wxLogInterposerTemp()
982 : wxLogChain(this)
983{
984 DetachOldLog();
985}
986
987#ifdef __VISUALC__
988 #pragma warning(default:4355)
989#endif // VC++
990
991// ============================================================================
992// Global functions/variables
993// ============================================================================
994
995// ----------------------------------------------------------------------------
996// static variables
997// ----------------------------------------------------------------------------
998
999bool wxLog::ms_bRepetCounting = false;
1000
1001wxLog *wxLog::ms_pLogger = NULL;
1002bool wxLog::ms_doLog = true;
1003bool wxLog::ms_bAutoCreate = true;
1004bool wxLog::ms_bVerbose = false;
1005
1006wxLogLevel wxLog::ms_logLevel = wxLOG_Max; // log everything by default
1007
1008size_t wxLog::ms_suspendCount = 0;
1009
1010wxString wxLog::ms_timestamp(wxS("%X")); // time only, no date
1011
1012#if WXWIN_COMPATIBILITY_2_8
1013wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
1014#endif // wxDEBUG_LEVEL
1015
1016// ----------------------------------------------------------------------------
1017// stdout error logging helper
1018// ----------------------------------------------------------------------------
1019
1020// helper function: wraps the message and justifies it under given position
1021// (looks more pretty on the terminal). Also adds newline at the end.
1022//
1023// TODO this is now disabled until I find a portable way of determining the
1024// terminal window size (ok, I found it but does anybody really cares?)
1025#ifdef LOG_PRETTY_WRAP
1026static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
1027{
1028 size_t nMax = 80; // FIXME
1029 size_t nStart = strlen(pszPrefix);
1030 fputs(pszPrefix, f);
1031
1032 size_t n;
1033 while ( *psz != '\0' ) {
1034 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
1035 putc(*psz++, f);
1036
1037 // wrapped?
1038 if ( *psz != '\0' ) {
1039 /*putc('\n', f);*/
1040 for ( n = 0; n < nStart; n++ )
1041 putc(' ', f);
1042
1043 // as we wrapped, squeeze all white space
1044 while ( isspace(*psz) )
1045 psz++;
1046 }
1047 }
1048
1049 putc('\n', f);
1050}
1051#endif //LOG_PRETTY_WRAP
1052
1053// ----------------------------------------------------------------------------
1054// error code/error message retrieval functions
1055// ----------------------------------------------------------------------------
1056
1057// get error code from syste
1058unsigned long wxSysErrorCode()
1059{
1060#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1061 return ::GetLastError();
1062#else //Unix
1063 return errno;
1064#endif //Win/Unix
1065}
1066
1067// get error message from system
1068const wxChar *wxSysErrorMsg(unsigned long nErrCode)
1069{
1070 if ( nErrCode == 0 )
1071 nErrCode = wxSysErrorCode();
1072
1073#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
1074 static wxChar s_szBuf[1024];
1075
1076 // get error message from system
1077 LPVOID lpMsgBuf;
1078 if ( ::FormatMessage
1079 (
1080 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
1081 NULL,
1082 nErrCode,
1083 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1084 (LPTSTR)&lpMsgBuf,
1085 0,
1086 NULL
1087 ) == 0 )
1088 {
1089 // if this happens, something is seriously wrong, so don't use _() here
1090 // for safety
1091 wxSprintf(s_szBuf, wxS("unknown error %lx"), nErrCode);
1092 return s_szBuf;
1093 }
1094
1095
1096 // copy it to our buffer and free memory
1097 // Crashes on SmartPhone (FIXME)
1098#if !defined(__SMARTPHONE__) /* of WinCE */
1099 if( lpMsgBuf != 0 )
1100 {
1101 wxStrlcpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf));
1102
1103 LocalFree(lpMsgBuf);
1104
1105 // returned string is capitalized and ended with '\r\n' - bad
1106 s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
1107 size_t len = wxStrlen(s_szBuf);
1108 if ( len > 0 ) {
1109 // truncate string
1110 if ( s_szBuf[len - 2] == wxS('\r') )
1111 s_szBuf[len - 2] = wxS('\0');
1112 }
1113 }
1114 else
1115#endif // !__SMARTPHONE__
1116 {
1117 s_szBuf[0] = wxS('\0');
1118 }
1119
1120 return s_szBuf;
1121#else // !__WINDOWS__
1122 #if wxUSE_UNICODE
1123 static wchar_t s_wzBuf[1024];
1124 wxConvCurrent->MB2WC(s_wzBuf, strerror((int)nErrCode),
1125 WXSIZEOF(s_wzBuf) - 1);
1126 return s_wzBuf;
1127 #else
1128 return strerror((int)nErrCode);
1129 #endif
1130#endif // __WINDOWS__/!__WINDOWS__
1131}
1132
1133#endif // wxUSE_LOG