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
;
81 // define static functions providing access to the critical sections we use
82 // instead of just using static critical section variables as log functions may
83 // be used during static initialization and while this is certainly not
84 // advisable it's still better to not crash (as we'd do if we used a yet
85 // uninitialized critical section) if it happens
87 // this critical section is used for buffering the messages from threads other
88 // than main, i.e. it protects all accesses to gs_bufferedLogRecords above
89 inline wxCriticalSection
& GetBackgroundLogCS()
91 static wxCriticalSection s_csBackground
;
93 return s_csBackground
;
96 inline wxCriticalSection
& GetTraceMaskCS()
98 static wxCriticalSection s_csTrace
;
103 inline wxCriticalSection
& GetPreviousLogCS()
105 static wxCriticalSection s_csPrev
;
110 inline wxCriticalSection
& GetLevelsCS()
112 static wxCriticalSection s_csLevels
;
117 } // anonymous namespace
119 #endif // wxUSE_THREADS
121 // ----------------------------------------------------------------------------
122 // non member functions
123 // ----------------------------------------------------------------------------
125 // define this to enable wrapping of log messages
126 //#define LOG_PRETTY_WRAP
128 #ifdef LOG_PRETTY_WRAP
129 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
132 // ----------------------------------------------------------------------------
134 // ----------------------------------------------------------------------------
139 // this struct is used to store information about the previous log message used
140 // by OnLog() to (optionally) avoid logging multiple copies of the same message
141 struct PreviousLogInfo
149 // previous message itself
155 // other information about it
156 wxLogRecordInfo info
;
158 // the number of times it was already repeated
159 unsigned numRepeated
;
162 PreviousLogInfo gs_prevLog
;
165 // map containing all components for which log level was explicitly set
167 // NB: all accesses to it must be protected by GetLevelsCS() critical section
168 wxStringToNumHashMap gs_componentLevels
;
170 } // anonymous namespace
172 // ============================================================================
174 // ============================================================================
176 // ----------------------------------------------------------------------------
177 // helper global functions
178 // ----------------------------------------------------------------------------
180 void wxSafeShowMessage(const wxString
& title
, const wxString
& text
)
183 ::MessageBox(NULL
, text
.t_str(), title
.t_str(), MB_OK
| MB_ICONSTOP
);
185 wxFprintf(stderr
, wxS("%s: %s\n"), title
.c_str(), text
.c_str());
190 // ----------------------------------------------------------------------------
191 // wxLog class implementation
192 // ----------------------------------------------------------------------------
194 unsigned wxLog::LogLastRepeatIfNeeded()
196 const unsigned count
= gs_prevLog
.numRepeated
;
198 if ( gs_prevLog
.numRepeated
)
202 msg
.Printf(wxPLURAL("The previous message repeated once.",
203 "The previous message repeated %lu times.",
204 gs_prevLog
.numRepeated
),
205 gs_prevLog
.numRepeated
);
207 msg
.Printf(wxS("The previous message was repeated %lu times."),
208 gs_prevLog
.numRepeated
);
210 gs_prevLog
.numRepeated
= 0;
211 gs_prevLog
.msg
.clear();
212 DoLogRecord(gs_prevLog
.level
, msg
, gs_prevLog
.info
);
220 // Flush() must be called before destroying the object as otherwise some
221 // messages could be lost
222 if ( gs_prevLog
.numRepeated
)
224 wxMessageOutputDebug().Printf
226 wxS("Last repeated message (\"%s\", %lu times) wasn't output"),
228 gs_prevLog
.numRepeated
233 // ----------------------------------------------------------------------------
234 // wxLog logging functions
235 // ----------------------------------------------------------------------------
239 wxLog::OnLog(wxLogLevel level
, const wxString
& msg
, time_t t
)
241 wxLogRecordInfo info
;
244 info
.threadId
= wxThread::GetCurrentId();
245 #endif // wxUSE_THREADS
247 OnLog(level
, msg
, info
);
252 wxLog::OnLog(wxLogLevel level
,
254 const wxLogRecordInfo
& info
)
256 // fatal errors can't be suppressed nor handled by the custom log target
257 // and always terminate the program
258 if ( level
== wxLOG_FatalError
)
260 wxSafeShowMessage(wxS("Fatal Error"), msg
);
269 wxLog
*pLogger
= GetActiveTarget();
274 if ( !wxThread::IsMain() )
276 wxCriticalSectionLocker
lock(GetBackgroundLogCS());
278 gs_bufferedLogRecords
.push_back(wxLogRecord(level
, msg
, info
));
280 // ensure that our Flush() will be called soon
285 #endif // wxUSE_THREADS
287 pLogger
->OnLogInMainThread(level
, msg
, info
);
291 wxLog::OnLogInMainThread(wxLogLevel level
,
293 const wxLogRecordInfo
& info
)
295 if ( GetRepetitionCounting() )
297 wxCRIT_SECT_LOCKER(lock
, GetPreviousLogCS());
299 if ( msg
== gs_prevLog
.msg
)
301 gs_prevLog
.numRepeated
++;
303 // nothing else to do, in particular, don't log the
308 LogLastRepeatIfNeeded();
310 // reset repetition counter for a new message
311 gs_prevLog
.msg
= msg
;
312 gs_prevLog
.level
= level
;
313 gs_prevLog
.info
= info
;
316 // handle extra data which may be passed to us by wxLogXXX()
317 wxString prefix
, suffix
;
319 if ( info
.GetNumValue(wxLOG_KEY_SYS_ERROR_CODE
, &num
) )
321 long err
= static_cast<long>(num
);
323 err
= wxSysErrorCode();
325 suffix
.Printf(_(" (error %ld: %s)"), err
, wxSysErrorMsg(err
));
330 if ( level
== wxLOG_Trace
&& info
.GetStrValue(wxLOG_KEY_TRACE_MASK
, &str
) )
332 prefix
= "(" + str
+ ") ";
334 #endif // wxUSE_LOG_TRACE
336 DoLogRecord(level
, prefix
+ msg
+ suffix
, info
);
339 void wxLog::DoLogRecord(wxLogLevel level
,
341 const wxLogRecordInfo
& info
)
343 #if WXWIN_COMPATIBILITY_2_8
344 // call the old DoLog() to ensure that existing custom log classes still
347 // as the user code could have defined it as either taking "const char *"
348 // (in ANSI build) or "const wxChar *" (in ANSI/Unicode), we have no choice
349 // but to call both of them
350 DoLog(level
, (const char*)msg
.mb_str(), info
.timestamp
);
351 DoLog(level
, (const wchar_t*)msg
.wc_str(), info
.timestamp
);
352 #endif // WXWIN_COMPATIBILITY_2_8
355 // TODO: it would be better to extract message formatting in a separate
356 // wxLogFormatter class but for now we hard code formatting here
360 // don't time stamp debug messages under MSW as debug viewers usually
361 // already have an option to do it
363 if ( level
!= wxLOG_Debug
&& level
!= wxLOG_Trace
)
367 // TODO: use the other wxLogRecordInfo fields
372 prefix
+= _("Error: ");
376 prefix
+= _("Warning: ");
379 // don't prepend "debug/trace" prefix under MSW as it goes to the debug
380 // window anyhow and so can't be confused with something else
383 // this prefix (as well as the one below) is intentionally not
384 // translated as nobody translates debug messages anyhow
394 DoLogTextAtLevel(level
, prefix
+ msg
);
397 void wxLog::DoLogTextAtLevel(wxLogLevel level
, const wxString
& msg
)
399 // we know about debug messages (because using wxMessageOutputDebug is the
400 // right thing to do in 99% of all cases and also for compatibility) but
401 // anything else needs to be handled in the derived class
402 if ( level
== wxLOG_Debug
|| level
== wxLOG_Trace
)
404 wxMessageOutputDebug().Output(msg
+ wxS('\n'));
412 void wxLog::DoLogText(const wxString
& WXUNUSED(msg
))
414 // in 2.8-compatible build the derived class might override DoLog() or
415 // DoLogString() instead so we can't have this assert there
416 #if !WXWIN_COMPATIBILITY_2_8
417 wxFAIL_MSG( "must be overridden if it is called" );
418 #endif // WXWIN_COMPATIBILITY_2_8
421 #if WXWIN_COMPATIBILITY_2_8
423 void wxLog::DoLog(wxLogLevel
WXUNUSED(level
), const char *szString
, time_t t
)
425 DoLogString(szString
, t
);
428 void wxLog::DoLog(wxLogLevel
WXUNUSED(level
), const wchar_t *wzString
, time_t t
)
430 DoLogString(wzString
, t
);
433 #endif // WXWIN_COMPATIBILITY_2_8
435 // ----------------------------------------------------------------------------
436 // wxLog active target management
437 // ----------------------------------------------------------------------------
439 wxLog
*wxLog::GetActiveTarget()
441 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
442 // prevent infinite recursion if someone calls wxLogXXX() from
443 // wxApp::CreateLogTarget()
444 static bool s_bInGetActiveTarget
= false;
445 if ( !s_bInGetActiveTarget
) {
446 s_bInGetActiveTarget
= true;
448 // ask the application to create a log target for us
449 if ( wxTheApp
!= NULL
)
450 ms_pLogger
= wxTheApp
->GetTraits()->CreateLogTarget();
452 ms_pLogger
= new wxLogStderr
;
454 s_bInGetActiveTarget
= false;
456 // do nothing if it fails - what can we do?
463 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
465 if ( ms_pLogger
!= NULL
) {
466 // flush the old messages before changing because otherwise they might
467 // get lost later if this target is not restored
471 wxLog
*pOldLogger
= ms_pLogger
;
472 ms_pLogger
= pLogger
;
477 void wxLog::DontCreateOnDemand()
479 ms_bAutoCreate
= false;
481 // this is usually called at the end of the program and we assume that it
482 // is *always* called at the end - so we free memory here to avoid false
483 // memory leak reports from wxWin memory tracking code
487 void wxLog::DoCreateOnDemand()
489 ms_bAutoCreate
= true;
492 // ----------------------------------------------------------------------------
493 // wxLog components levels
494 // ----------------------------------------------------------------------------
497 void wxLog::SetComponentLevel(const wxString
& component
, wxLogLevel level
)
499 if ( component
.empty() )
505 wxCRIT_SECT_LOCKER(lock
, GetLevelsCS());
507 gs_componentLevels
[component
] = level
;
512 wxLogLevel
wxLog::GetComponentLevel(wxString component
)
514 wxCRIT_SECT_LOCKER(lock
, GetLevelsCS());
516 while ( !component
.empty() )
518 wxStringToNumHashMap::const_iterator
519 it
= gs_componentLevels
.find(component
);
520 if ( it
!= gs_componentLevels
.end() )
521 return static_cast<wxLogLevel
>(it
->second
);
523 component
= component
.BeforeLast('/');
526 return GetLogLevel();
529 // ----------------------------------------------------------------------------
531 // ----------------------------------------------------------------------------
533 void wxLog::AddTraceMask(const wxString
& str
)
535 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
537 ms_aTraceMasks
.push_back(str
);
540 void wxLog::RemoveTraceMask(const wxString
& str
)
542 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
544 int index
= ms_aTraceMasks
.Index(str
);
545 if ( index
!= wxNOT_FOUND
)
546 ms_aTraceMasks
.RemoveAt((size_t)index
);
549 void wxLog::ClearTraceMasks()
551 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
553 ms_aTraceMasks
.Clear();
556 /*static*/ bool wxLog::IsAllowedTraceMask(const wxString
& mask
)
558 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
560 for ( wxArrayString::iterator it
= ms_aTraceMasks
.begin(),
561 en
= ms_aTraceMasks
.end();
571 // ----------------------------------------------------------------------------
572 // wxLog miscellaneous other methods
573 // ----------------------------------------------------------------------------
575 void wxLog::TimeStamp(wxString
*str
)
578 if ( !ms_timestamp
.empty() )
582 (void)time(&timeNow
);
585 wxStrftime(buf
, WXSIZEOF(buf
),
586 ms_timestamp
, wxLocaltime_r(&timeNow
, &tm
));
589 *str
<< buf
<< wxS(": ");
591 #endif // wxUSE_DATETIME
597 wxASSERT_MSG( wxThread::IsMain(),
598 "should be called from the main thread only" );
600 // check if we have queued messages from other threads
601 wxLogRecords bufferedLogRecords
;
604 wxCriticalSectionLocker
lock(GetBackgroundLogCS());
605 bufferedLogRecords
.swap(gs_bufferedLogRecords
);
607 // release the lock now to not keep it while we are logging the
608 // messages below, allowing background threads to run
611 if ( !bufferedLogRecords
.empty() )
613 for ( wxLogRecords::const_iterator it
= bufferedLogRecords
.begin();
614 it
!= bufferedLogRecords
.end();
617 OnLogInMainThread(it
->level
, it
->msg
, it
->info
);
620 #endif // wxUSE_THREADS
622 LogLastRepeatIfNeeded();
625 // ----------------------------------------------------------------------------
626 // wxLogBuffer implementation
627 // ----------------------------------------------------------------------------
629 void wxLogBuffer::Flush()
633 if ( !m_str
.empty() )
635 wxMessageOutputBest out
;
636 out
.Printf(wxS("%s"), m_str
.c_str());
641 void wxLogBuffer::DoLogTextAtLevel(wxLogLevel level
, const wxString
& msg
)
643 // don't put debug messages in the buffer, we don't want to show
644 // them to the user in a msg box, log them immediately
649 wxLog::DoLogTextAtLevel(level
, msg
);
653 m_str
<< msg
<< wxS("\n");
657 // ----------------------------------------------------------------------------
658 // wxLogStderr class implementation
659 // ----------------------------------------------------------------------------
661 wxLogStderr::wxLogStderr(FILE *fp
)
669 void wxLogStderr::DoLogText(const wxString
& msg
)
671 wxFputs(msg
+ '\n', m_fp
);
674 // under GUI systems such as Windows or Mac, programs usually don't have
675 // stderr at all, so show the messages also somewhere else, typically in
676 // the debugger window so that they go at least somewhere instead of being
678 if ( m_fp
== stderr
)
680 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
681 if ( traits
&& !traits
->HasStderr() )
683 wxMessageOutputDebug().Output(msg
+ wxS('\n'));
688 // ----------------------------------------------------------------------------
689 // wxLogStream implementation
690 // ----------------------------------------------------------------------------
692 #if wxUSE_STD_IOSTREAM
693 #include "wx/ioswrap.h"
694 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
697 m_ostr
= &wxSTD cerr
;
702 void wxLogStream::DoLogText(const wxString
& msg
)
704 (*m_ostr
) << msg
<< wxSTD endl
;
706 #endif // wxUSE_STD_IOSTREAM
708 // ----------------------------------------------------------------------------
710 // ----------------------------------------------------------------------------
712 wxLogChain::wxLogChain(wxLog
*logger
)
714 m_bPassMessages
= true;
717 m_logOld
= wxLog::SetActiveTarget(this);
720 wxLogChain::~wxLogChain()
724 if ( m_logNew
!= this )
728 void wxLogChain::SetLog(wxLog
*logger
)
730 if ( m_logNew
!= this )
736 void wxLogChain::Flush()
741 // be careful to avoid infinite recursion
742 if ( m_logNew
&& m_logNew
!= this )
746 void wxLogChain::DoLogRecord(wxLogLevel level
,
748 const wxLogRecordInfo
& info
)
750 // let the previous logger show it
751 if ( m_logOld
&& IsPassingMessages() )
752 m_logOld
->LogRecord(level
, msg
, info
);
754 // and also send it to the new one
755 if ( m_logNew
&& m_logNew
!= this )
756 m_logNew
->LogRecord(level
, msg
, info
);
760 // "'this' : used in base member initializer list" - so what?
761 #pragma warning(disable:4355)
764 // ----------------------------------------------------------------------------
766 // ----------------------------------------------------------------------------
768 wxLogInterposer::wxLogInterposer()
773 // ----------------------------------------------------------------------------
774 // wxLogInterposerTemp
775 // ----------------------------------------------------------------------------
777 wxLogInterposerTemp::wxLogInterposerTemp()
784 #pragma warning(default:4355)
787 // ============================================================================
788 // Global functions/variables
789 // ============================================================================
791 // ----------------------------------------------------------------------------
793 // ----------------------------------------------------------------------------
795 bool wxLog::ms_bRepetCounting
= false;
797 wxLog
*wxLog::ms_pLogger
= NULL
;
798 bool wxLog::ms_doLog
= true;
799 bool wxLog::ms_bAutoCreate
= true;
800 bool wxLog::ms_bVerbose
= false;
802 wxLogLevel
wxLog::ms_logLevel
= wxLOG_Max
; // log everything by default
804 size_t wxLog::ms_suspendCount
= 0;
806 wxString
wxLog::ms_timestamp(wxS("%X")); // time only, no date
808 #if WXWIN_COMPATIBILITY_2_8
809 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
810 #endif // wxDEBUG_LEVEL
812 wxArrayString
wxLog::ms_aTraceMasks
;
814 // ----------------------------------------------------------------------------
815 // stdout error logging helper
816 // ----------------------------------------------------------------------------
818 // helper function: wraps the message and justifies it under given position
819 // (looks more pretty on the terminal). Also adds newline at the end.
821 // TODO this is now disabled until I find a portable way of determining the
822 // terminal window size (ok, I found it but does anybody really cares?)
823 #ifdef LOG_PRETTY_WRAP
824 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
826 size_t nMax
= 80; // FIXME
827 size_t nStart
= strlen(pszPrefix
);
831 while ( *psz
!= '\0' ) {
832 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
836 if ( *psz
!= '\0' ) {
838 for ( n
= 0; n
< nStart
; n
++ )
841 // as we wrapped, squeeze all white space
842 while ( isspace(*psz
) )
849 #endif //LOG_PRETTY_WRAP
851 // ----------------------------------------------------------------------------
852 // error code/error message retrieval functions
853 // ----------------------------------------------------------------------------
855 // get error code from syste
856 unsigned long wxSysErrorCode()
858 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
859 return ::GetLastError();
865 // get error message from system
866 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
869 nErrCode
= wxSysErrorCode();
871 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
872 static wxChar s_szBuf
[1024];
874 // get error message from system
878 FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
881 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
887 // if this happens, something is seriously wrong, so don't use _() here
889 wxSprintf(s_szBuf
, wxS("unknown error %lx"), nErrCode
);
894 // copy it to our buffer and free memory
895 // Crashes on SmartPhone (FIXME)
896 #if !defined(__SMARTPHONE__) /* of WinCE */
899 wxStrlcpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
));
903 // returned string is capitalized and ended with '\r\n' - bad
904 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
905 size_t len
= wxStrlen(s_szBuf
);
908 if ( s_szBuf
[len
- 2] == wxS('\r') )
909 s_szBuf
[len
- 2] = wxS('\0');
913 #endif // !__SMARTPHONE__
915 s_szBuf
[0] = wxS('\0');
921 static wchar_t s_wzBuf
[1024];
922 wxConvCurrent
->MB2WC(s_wzBuf
, strerror((int)nErrCode
),
923 WXSIZEOF(s_wzBuf
) - 1);
926 return strerror((int)nErrCode
);
928 #endif // __WXMSW__/!__WXMSW__