1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/log.cpp
3 // Purpose: Assorted wxLogXXX functions, and wxLog (sink for logs)
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
33 #include "wx/arrstr.h"
35 #include "wx/string.h"
39 #include "wx/apptrait.h"
40 #include "wx/datetime.h"
42 #include "wx/msgout.h"
43 #include "wx/textfile.h"
44 #include "wx/thread.h"
46 #include "wx/vector.h"
48 // other standard headers
59 #include "wx/msw/wince/time.h"
61 #endif /* ! __WXPALMOS5__ */
63 #if defined(__WINDOWS__)
64 #include "wx/msw/private.h" // includes windows.h
67 #undef wxLOG_COMPONENT
68 const char *wxLOG_COMPONENT
= "";
75 // contains messages logged by the other threads and waiting to be shown until
76 // Flush() is called in the main one
77 typedef wxVector
<wxLogRecord
> wxLogRecords
;
78 wxLogRecords gs_bufferedLogRecords
;
80 // this macro allows to define an object which will be initialized before any
81 // other function in this file is called: this is necessary to allow log
82 // functions to be used during static initialization (this is not advisable
83 // anyhow but we should at least try to not crash) and to also ensure that they
84 // are initialized by the time static initialization is done, i.e. before any
85 // threads are created hopefully
87 // the net effect of all this is that you can use Get##name##CS() function to
88 // access the critical function without worrying about it being not initialized
90 // see also WX_DEFINE_GLOBAL_CONV2() in src/common/strconv.cpp
91 #define WX_DEFINE_LOG_CS(name) \
92 inline wxCriticalSection& Get##name##CS() \
94 static wxCriticalSection s_cs##name; \
98 wxCriticalSection *gs_##name##CSPtr = &Get##name##CS()
100 // this critical section is used for buffering the messages from threads other
101 // than main, i.e. it protects all accesses to gs_bufferedLogRecords above
102 WX_DEFINE_LOG_CS(BackgroundLog
);
104 // this one is used for protecting ms_aTraceMasks from concurrent access
105 WX_DEFINE_LOG_CS(TraceMask
);
107 // and this one is used for gs_componentLevels
108 WX_DEFINE_LOG_CS(Levels
);
110 } // anonymous namespace
112 #endif // wxUSE_THREADS
114 // ----------------------------------------------------------------------------
115 // non member functions
116 // ----------------------------------------------------------------------------
118 // define this to enable wrapping of log messages
119 //#define LOG_PRETTY_WRAP
121 #ifdef LOG_PRETTY_WRAP
122 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
125 // ----------------------------------------------------------------------------
127 // ----------------------------------------------------------------------------
132 // this struct is used to store information about the previous log message used
133 // by OnLog() to (optionally) avoid logging multiple copies of the same message
134 struct PreviousLogInfo
142 // previous message itself
148 // other information about it
149 wxLogRecordInfo info
;
151 // the number of times it was already repeated
152 unsigned numRepeated
;
155 PreviousLogInfo gs_prevLog
;
158 // map containing all components for which log level was explicitly set
160 // NB: all accesses to it must be protected by GetLevelsCS() critical section
161 wxStringToNumHashMap gs_componentLevels
;
163 } // anonymous namespace
165 // ============================================================================
167 // ============================================================================
169 // ----------------------------------------------------------------------------
170 // helper global functions
171 // ----------------------------------------------------------------------------
173 void wxSafeShowMessage(const wxString
& title
, const wxString
& text
)
176 ::MessageBox(NULL
, text
.t_str(), title
.t_str(), MB_OK
| MB_ICONSTOP
);
178 wxFprintf(stderr
, wxS("%s: %s\n"), title
.c_str(), text
.c_str());
183 // ----------------------------------------------------------------------------
184 // wxLog class implementation
185 // ----------------------------------------------------------------------------
187 unsigned wxLog::LogLastRepeatIfNeeded()
189 const unsigned count
= gs_prevLog
.numRepeated
;
191 if ( gs_prevLog
.numRepeated
)
195 msg
.Printf(wxPLURAL("The previous message repeated once.",
196 "The previous message repeated %lu times.",
197 gs_prevLog
.numRepeated
),
198 gs_prevLog
.numRepeated
);
200 msg
.Printf(wxS("The previous message was repeated %lu times."),
201 gs_prevLog
.numRepeated
);
203 gs_prevLog
.numRepeated
= 0;
204 gs_prevLog
.msg
.clear();
205 DoLogRecord(gs_prevLog
.level
, msg
, gs_prevLog
.info
);
213 // Flush() must be called before destroying the object as otherwise some
214 // messages could be lost
215 if ( gs_prevLog
.numRepeated
)
217 wxMessageOutputDebug().Printf
219 wxS("Last repeated message (\"%s\", %lu times) wasn't output"),
221 gs_prevLog
.numRepeated
226 // ----------------------------------------------------------------------------
227 // wxLog logging functions
228 // ----------------------------------------------------------------------------
232 wxLog::OnLog(wxLogLevel level
, const wxString
& msg
, time_t t
)
234 wxLogRecordInfo info
;
237 info
.threadId
= wxThread::GetCurrentId();
238 #endif // wxUSE_THREADS
240 OnLog(level
, msg
, info
);
245 wxLog::OnLog(wxLogLevel level
,
247 const wxLogRecordInfo
& info
)
249 // fatal errors can't be suppressed nor handled by the custom log target
250 // and always terminate the program
251 if ( level
== wxLOG_FatalError
)
253 wxSafeShowMessage(wxS("Fatal Error"), msg
);
262 wxLog
*pLogger
= GetActiveTarget();
267 if ( !wxThread::IsMain() )
269 wxCriticalSectionLocker
lock(GetBackgroundLogCS());
271 gs_bufferedLogRecords
.push_back(wxLogRecord(level
, msg
, info
));
273 // ensure that our Flush() will be called soon
278 #endif // wxUSE_THREADS
280 pLogger
->OnLogInMainThread(level
, msg
, info
);
284 wxLog::OnLogInMainThread(wxLogLevel level
,
286 const wxLogRecordInfo
& info
)
288 if ( GetRepetitionCounting() )
290 if ( msg
== gs_prevLog
.msg
)
292 gs_prevLog
.numRepeated
++;
294 // nothing else to do, in particular, don't log the
299 LogLastRepeatIfNeeded();
301 // reset repetition counter for a new message
302 gs_prevLog
.msg
= msg
;
303 gs_prevLog
.level
= level
;
304 gs_prevLog
.info
= info
;
307 // handle extra data which may be passed to us by wxLogXXX()
308 wxString prefix
, suffix
;
310 if ( info
.GetNumValue(wxLOG_KEY_SYS_ERROR_CODE
, &num
) )
312 long err
= static_cast<long>(num
);
314 err
= wxSysErrorCode();
316 suffix
.Printf(_(" (error %ld: %s)"), err
, wxSysErrorMsg(err
));
321 if ( level
== wxLOG_Trace
&& info
.GetStrValue(wxLOG_KEY_TRACE_MASK
, &str
) )
323 prefix
= "(" + str
+ ") ";
325 #endif // wxUSE_LOG_TRACE
327 DoLogRecord(level
, prefix
+ msg
+ suffix
, info
);
330 void wxLog::DoLogRecord(wxLogLevel level
,
332 const wxLogRecordInfo
& info
)
334 #if WXWIN_COMPATIBILITY_2_8
335 // call the old DoLog() to ensure that existing custom log classes still
338 // as the user code could have defined it as either taking "const char *"
339 // (in ANSI build) or "const wxChar *" (in ANSI/Unicode), we have no choice
340 // but to call both of them
341 DoLog(level
, (const char*)msg
.mb_str(), info
.timestamp
);
342 DoLog(level
, (const wchar_t*)msg
.wc_str(), info
.timestamp
);
343 #endif // WXWIN_COMPATIBILITY_2_8
346 // TODO: it would be better to extract message formatting in a separate
347 // wxLogFormatter class but for now we hard code formatting here
351 // don't time stamp debug messages under MSW as debug viewers usually
352 // already have an option to do it
354 if ( level
!= wxLOG_Debug
&& level
!= wxLOG_Trace
)
358 // TODO: use the other wxLogRecordInfo fields
363 prefix
+= _("Error: ");
367 prefix
+= _("Warning: ");
370 // don't prepend "debug/trace" prefix under MSW as it goes to the debug
371 // window anyhow and so can't be confused with something else
374 // this prefix (as well as the one below) is intentionally not
375 // translated as nobody translates debug messages anyhow
385 DoLogTextAtLevel(level
, prefix
+ msg
);
388 void wxLog::DoLogTextAtLevel(wxLogLevel level
, const wxString
& msg
)
390 // we know about debug messages (because using wxMessageOutputDebug is the
391 // right thing to do in 99% of all cases and also for compatibility) but
392 // anything else needs to be handled in the derived class
393 if ( level
== wxLOG_Debug
|| level
== wxLOG_Trace
)
395 wxMessageOutputDebug().Output(msg
+ wxS('\n'));
403 void wxLog::DoLogText(const wxString
& WXUNUSED(msg
))
405 // in 2.8-compatible build the derived class might override DoLog() or
406 // DoLogString() instead so we can't have this assert there
407 #if !WXWIN_COMPATIBILITY_2_8
408 wxFAIL_MSG( "must be overridden if it is called" );
409 #endif // WXWIN_COMPATIBILITY_2_8
412 #if WXWIN_COMPATIBILITY_2_8
414 void wxLog::DoLog(wxLogLevel
WXUNUSED(level
), const char *szString
, time_t t
)
416 DoLogString(szString
, t
);
419 void wxLog::DoLog(wxLogLevel
WXUNUSED(level
), const wchar_t *wzString
, time_t t
)
421 DoLogString(wzString
, t
);
424 #endif // WXWIN_COMPATIBILITY_2_8
426 // ----------------------------------------------------------------------------
427 // wxLog active target management
428 // ----------------------------------------------------------------------------
430 wxLog
*wxLog::GetActiveTarget()
432 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
433 // prevent infinite recursion if someone calls wxLogXXX() from
434 // wxApp::CreateLogTarget()
435 static bool s_bInGetActiveTarget
= false;
436 if ( !s_bInGetActiveTarget
) {
437 s_bInGetActiveTarget
= true;
439 // ask the application to create a log target for us
440 if ( wxTheApp
!= NULL
)
441 ms_pLogger
= wxTheApp
->GetTraits()->CreateLogTarget();
443 ms_pLogger
= new wxLogStderr
;
445 s_bInGetActiveTarget
= false;
447 // do nothing if it fails - what can we do?
454 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
456 if ( ms_pLogger
!= NULL
) {
457 // flush the old messages before changing because otherwise they might
458 // get lost later if this target is not restored
462 wxLog
*pOldLogger
= ms_pLogger
;
463 ms_pLogger
= pLogger
;
468 void wxLog::DontCreateOnDemand()
470 ms_bAutoCreate
= false;
472 // this is usually called at the end of the program and we assume that it
473 // is *always* called at the end - so we free memory here to avoid false
474 // memory leak reports from wxWin memory tracking code
478 void wxLog::DoCreateOnDemand()
480 ms_bAutoCreate
= true;
483 // ----------------------------------------------------------------------------
484 // wxLog components levels
485 // ----------------------------------------------------------------------------
488 void wxLog::SetComponentLevel(const wxString
& component
, wxLogLevel level
)
490 if ( component
.empty() )
496 wxCRIT_SECT_LOCKER(lock
, GetLevelsCS());
498 gs_componentLevels
[component
] = level
;
503 wxLogLevel
wxLog::GetComponentLevel(wxString component
)
505 wxCRIT_SECT_LOCKER(lock
, GetLevelsCS());
507 while ( !component
.empty() )
509 wxStringToNumHashMap::const_iterator
510 it
= gs_componentLevels
.find(component
);
511 if ( it
!= gs_componentLevels
.end() )
512 return static_cast<wxLogLevel
>(it
->second
);
514 component
= component
.BeforeLast('/');
517 return GetLogLevel();
520 // ----------------------------------------------------------------------------
522 // ----------------------------------------------------------------------------
524 void wxLog::AddTraceMask(const wxString
& str
)
526 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
528 ms_aTraceMasks
.push_back(str
);
531 void wxLog::RemoveTraceMask(const wxString
& str
)
533 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
535 int index
= ms_aTraceMasks
.Index(str
);
536 if ( index
!= wxNOT_FOUND
)
537 ms_aTraceMasks
.RemoveAt((size_t)index
);
540 void wxLog::ClearTraceMasks()
542 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
544 ms_aTraceMasks
.Clear();
547 /*static*/ bool wxLog::IsAllowedTraceMask(const wxString
& mask
)
549 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
551 for ( wxArrayString::iterator it
= ms_aTraceMasks
.begin(),
552 en
= ms_aTraceMasks
.end();
562 // ----------------------------------------------------------------------------
563 // wxLog miscellaneous other methods
564 // ----------------------------------------------------------------------------
566 void wxLog::TimeStamp(wxString
*str
)
569 if ( !ms_timestamp
.empty() )
573 (void)time(&timeNow
);
576 wxStrftime(buf
, WXSIZEOF(buf
),
577 ms_timestamp
, wxLocaltime_r(&timeNow
, &tm
));
580 *str
<< buf
<< wxS(": ");
582 #endif // wxUSE_DATETIME
588 wxASSERT_MSG( wxThread::IsMain(),
589 "should be called from the main thread only" );
591 // check if we have queued messages from other threads
592 wxLogRecords bufferedLogRecords
;
595 wxCriticalSectionLocker
lock(GetBackgroundLogCS());
596 bufferedLogRecords
.swap(gs_bufferedLogRecords
);
598 // release the lock now to not keep it while we are logging the
599 // messages below, allowing background threads to run
602 if ( !bufferedLogRecords
.empty() )
604 for ( wxLogRecords::const_iterator it
= bufferedLogRecords
.begin();
605 it
!= bufferedLogRecords
.end();
608 OnLogInMainThread(it
->level
, it
->msg
, it
->info
);
611 #endif // wxUSE_THREADS
613 LogLastRepeatIfNeeded();
616 // ----------------------------------------------------------------------------
617 // wxLogBuffer implementation
618 // ----------------------------------------------------------------------------
620 void wxLogBuffer::Flush()
624 if ( !m_str
.empty() )
626 wxMessageOutputBest out
;
627 out
.Printf(wxS("%s"), m_str
.c_str());
632 void wxLogBuffer::DoLogTextAtLevel(wxLogLevel level
, const wxString
& msg
)
634 // don't put debug messages in the buffer, we don't want to show
635 // them to the user in a msg box, log them immediately
640 wxLog::DoLogTextAtLevel(level
, msg
);
644 m_str
<< msg
<< wxS("\n");
648 // ----------------------------------------------------------------------------
649 // wxLogStderr class implementation
650 // ----------------------------------------------------------------------------
652 wxLogStderr::wxLogStderr(FILE *fp
)
660 void wxLogStderr::DoLogText(const wxString
& msg
)
662 wxFputs(msg
+ '\n', m_fp
);
665 // under GUI systems such as Windows or Mac, programs usually don't have
666 // stderr at all, so show the messages also somewhere else, typically in
667 // the debugger window so that they go at least somewhere instead of being
669 if ( m_fp
== stderr
)
671 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
672 if ( traits
&& !traits
->HasStderr() )
674 wxMessageOutputDebug().Output(msg
+ wxS('\n'));
679 // ----------------------------------------------------------------------------
680 // wxLogStream implementation
681 // ----------------------------------------------------------------------------
683 #if wxUSE_STD_IOSTREAM
684 #include "wx/ioswrap.h"
685 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
688 m_ostr
= &wxSTD cerr
;
693 void wxLogStream::DoLogText(const wxString
& msg
)
695 (*m_ostr
) << msg
<< wxSTD endl
;
697 #endif // wxUSE_STD_IOSTREAM
699 // ----------------------------------------------------------------------------
701 // ----------------------------------------------------------------------------
703 wxLogChain::wxLogChain(wxLog
*logger
)
705 m_bPassMessages
= true;
708 m_logOld
= wxLog::SetActiveTarget(this);
711 wxLogChain::~wxLogChain()
715 if ( m_logNew
!= this )
719 void wxLogChain::SetLog(wxLog
*logger
)
721 if ( m_logNew
!= this )
727 void wxLogChain::Flush()
732 // be careful to avoid infinite recursion
733 if ( m_logNew
&& m_logNew
!= this )
737 void wxLogChain::DoLogRecord(wxLogLevel level
,
739 const wxLogRecordInfo
& info
)
741 // let the previous logger show it
742 if ( m_logOld
&& IsPassingMessages() )
743 m_logOld
->LogRecord(level
, msg
, info
);
745 // and also send it to the new one
746 if ( m_logNew
&& m_logNew
!= this )
747 m_logNew
->LogRecord(level
, msg
, info
);
751 // "'this' : used in base member initializer list" - so what?
752 #pragma warning(disable:4355)
755 // ----------------------------------------------------------------------------
757 // ----------------------------------------------------------------------------
759 wxLogInterposer::wxLogInterposer()
764 // ----------------------------------------------------------------------------
765 // wxLogInterposerTemp
766 // ----------------------------------------------------------------------------
768 wxLogInterposerTemp::wxLogInterposerTemp()
775 #pragma warning(default:4355)
778 // ============================================================================
779 // Global functions/variables
780 // ============================================================================
782 // ----------------------------------------------------------------------------
784 // ----------------------------------------------------------------------------
786 bool wxLog::ms_bRepetCounting
= false;
788 wxLog
*wxLog::ms_pLogger
= NULL
;
789 bool wxLog::ms_doLog
= true;
790 bool wxLog::ms_bAutoCreate
= true;
791 bool wxLog::ms_bVerbose
= false;
793 wxLogLevel
wxLog::ms_logLevel
= wxLOG_Max
; // log everything by default
795 size_t wxLog::ms_suspendCount
= 0;
797 wxString
wxLog::ms_timestamp(wxS("%X")); // time only, no date
799 #if WXWIN_COMPATIBILITY_2_8
800 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
801 #endif // wxDEBUG_LEVEL
803 wxArrayString
wxLog::ms_aTraceMasks
;
805 // ----------------------------------------------------------------------------
806 // stdout error logging helper
807 // ----------------------------------------------------------------------------
809 // helper function: wraps the message and justifies it under given position
810 // (looks more pretty on the terminal). Also adds newline at the end.
812 // TODO this is now disabled until I find a portable way of determining the
813 // terminal window size (ok, I found it but does anybody really cares?)
814 #ifdef LOG_PRETTY_WRAP
815 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
817 size_t nMax
= 80; // FIXME
818 size_t nStart
= strlen(pszPrefix
);
822 while ( *psz
!= '\0' ) {
823 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
827 if ( *psz
!= '\0' ) {
829 for ( n
= 0; n
< nStart
; n
++ )
832 // as we wrapped, squeeze all white space
833 while ( isspace(*psz
) )
840 #endif //LOG_PRETTY_WRAP
842 // ----------------------------------------------------------------------------
843 // error code/error message retrieval functions
844 // ----------------------------------------------------------------------------
846 // get error code from syste
847 unsigned long wxSysErrorCode()
849 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
850 return ::GetLastError();
856 // get error message from system
857 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
860 nErrCode
= wxSysErrorCode();
862 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
863 static wxChar s_szBuf
[1024];
865 // get error message from system
869 FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
872 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
878 // if this happens, something is seriously wrong, so don't use _() here
880 wxSprintf(s_szBuf
, wxS("unknown error %lx"), nErrCode
);
885 // copy it to our buffer and free memory
886 // Crashes on SmartPhone (FIXME)
887 #if !defined(__SMARTPHONE__) /* of WinCE */
890 wxStrlcpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
));
894 // returned string is capitalized and ended with '\r\n' - bad
895 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
896 size_t len
= wxStrlen(s_szBuf
);
899 if ( s_szBuf
[len
- 2] == wxS('\r') )
900 s_szBuf
[len
- 2] = wxS('\0');
904 #endif // !__SMARTPHONE__
906 s_szBuf
[0] = wxS('\0');
912 static wchar_t s_wzBuf
[1024];
913 wxConvCurrent
->MB2WC(s_wzBuf
, strerror((int)nErrCode
),
914 WXSIZEOF(s_wzBuf
) - 1);
917 return strerror((int)nErrCode
);
919 #endif // __WXMSW__/!__WXMSW__