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 wxCRIT_SECT_LOCKER(lock
, GetPreviousLogCS());
198 return LogLastRepeatIfNeededUnlocked();
201 unsigned wxLog::LogLastRepeatIfNeededUnlocked()
203 const unsigned count
= gs_prevLog
.numRepeated
;
205 if ( gs_prevLog
.numRepeated
)
209 msg
.Printf(wxPLURAL("The previous message repeated once.",
210 "The previous message repeated %lu times.",
211 gs_prevLog
.numRepeated
),
212 gs_prevLog
.numRepeated
);
214 msg
.Printf(wxS("The previous message was repeated %lu times."),
215 gs_prevLog
.numRepeated
);
217 gs_prevLog
.numRepeated
= 0;
218 gs_prevLog
.msg
.clear();
219 DoLogRecord(gs_prevLog
.level
, msg
, gs_prevLog
.info
);
227 // Flush() must be called before destroying the object as otherwise some
228 // messages could be lost
229 if ( gs_prevLog
.numRepeated
)
231 wxMessageOutputDebug().Printf
233 wxS("Last repeated message (\"%s\", %lu times) wasn't output"),
235 gs_prevLog
.numRepeated
240 // ----------------------------------------------------------------------------
241 // wxLog logging functions
242 // ----------------------------------------------------------------------------
246 wxLog::OnLog(wxLogLevel level
, const wxString
& msg
, time_t t
)
248 wxLogRecordInfo info
;
251 info
.threadId
= wxThread::GetCurrentId();
252 #endif // wxUSE_THREADS
254 OnLog(level
, msg
, info
);
259 wxLog::OnLog(wxLogLevel level
,
261 const wxLogRecordInfo
& info
)
263 // fatal errors can't be suppressed nor handled by the custom log target
264 // and always terminate the program
265 if ( level
== wxLOG_FatalError
)
267 wxSafeShowMessage(wxS("Fatal Error"), msg
);
276 wxLog
*pLogger
= GetActiveTarget();
281 if ( !wxThread::IsMain() )
283 wxCriticalSectionLocker
lock(GetBackgroundLogCS());
285 gs_bufferedLogRecords
.push_back(wxLogRecord(level
, msg
, info
));
287 // ensure that our Flush() will be called soon
292 #endif // wxUSE_THREADS
294 pLogger
->OnLogInMainThread(level
, msg
, info
);
298 wxLog::OnLogInMainThread(wxLogLevel level
,
300 const wxLogRecordInfo
& info
)
302 if ( GetRepetitionCounting() )
304 wxCRIT_SECT_LOCKER(lock
, GetPreviousLogCS());
306 if ( msg
== gs_prevLog
.msg
)
308 gs_prevLog
.numRepeated
++;
310 // nothing else to do, in particular, don't log the
315 LogLastRepeatIfNeededUnlocked();
317 // reset repetition counter for a new message
318 gs_prevLog
.msg
= msg
;
319 gs_prevLog
.level
= level
;
320 gs_prevLog
.info
= info
;
323 // handle extra data which may be passed to us by wxLogXXX()
324 wxString prefix
, suffix
;
326 if ( info
.GetNumValue(wxLOG_KEY_SYS_ERROR_CODE
, &num
) )
328 long err
= static_cast<long>(num
);
330 err
= wxSysErrorCode();
332 suffix
.Printf(_(" (error %ld: %s)"), err
, wxSysErrorMsg(err
));
337 if ( level
== wxLOG_Trace
&& info
.GetStrValue(wxLOG_KEY_TRACE_MASK
, &str
) )
339 prefix
= "(" + str
+ ") ";
341 #endif // wxUSE_LOG_TRACE
343 DoLogRecord(level
, prefix
+ msg
+ suffix
, info
);
346 void wxLog::DoLogRecord(wxLogLevel level
,
348 const wxLogRecordInfo
& info
)
350 #if WXWIN_COMPATIBILITY_2_8
351 // call the old DoLog() to ensure that existing custom log classes still
354 // as the user code could have defined it as either taking "const char *"
355 // (in ANSI build) or "const wxChar *" (in ANSI/Unicode), we have no choice
356 // but to call both of them
357 DoLog(level
, (const char*)msg
.mb_str(), info
.timestamp
);
358 DoLog(level
, (const wchar_t*)msg
.wc_str(), info
.timestamp
);
359 #endif // WXWIN_COMPATIBILITY_2_8
362 // TODO: it would be better to extract message formatting in a separate
363 // wxLogFormatter class but for now we hard code formatting here
367 // don't time stamp debug messages under MSW as debug viewers usually
368 // already have an option to do it
370 if ( level
!= wxLOG_Debug
&& level
!= wxLOG_Trace
)
374 // TODO: use the other wxLogRecordInfo fields
379 prefix
+= _("Error: ");
383 prefix
+= _("Warning: ");
386 // don't prepend "debug/trace" prefix under MSW as it goes to the debug
387 // window anyhow and so can't be confused with something else
390 // this prefix (as well as the one below) is intentionally not
391 // translated as nobody translates debug messages anyhow
401 DoLogTextAtLevel(level
, prefix
+ msg
);
404 void wxLog::DoLogTextAtLevel(wxLogLevel level
, const wxString
& msg
)
406 // we know about debug messages (because using wxMessageOutputDebug is the
407 // right thing to do in 99% of all cases and also for compatibility) but
408 // anything else needs to be handled in the derived class
409 if ( level
== wxLOG_Debug
|| level
== wxLOG_Trace
)
411 wxMessageOutputDebug().Output(msg
+ wxS('\n'));
419 void wxLog::DoLogText(const wxString
& WXUNUSED(msg
))
421 // in 2.8-compatible build the derived class might override DoLog() or
422 // DoLogString() instead so we can't have this assert there
423 #if !WXWIN_COMPATIBILITY_2_8
424 wxFAIL_MSG( "must be overridden if it is called" );
425 #endif // WXWIN_COMPATIBILITY_2_8
428 #if WXWIN_COMPATIBILITY_2_8
430 void wxLog::DoLog(wxLogLevel
WXUNUSED(level
), const char *szString
, time_t t
)
432 DoLogString(szString
, t
);
435 void wxLog::DoLog(wxLogLevel
WXUNUSED(level
), const wchar_t *wzString
, time_t t
)
437 DoLogString(wzString
, t
);
440 #endif // WXWIN_COMPATIBILITY_2_8
442 // ----------------------------------------------------------------------------
443 // wxLog active target management
444 // ----------------------------------------------------------------------------
446 wxLog
*wxLog::GetActiveTarget()
448 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
449 // prevent infinite recursion if someone calls wxLogXXX() from
450 // wxApp::CreateLogTarget()
451 static bool s_bInGetActiveTarget
= false;
452 if ( !s_bInGetActiveTarget
) {
453 s_bInGetActiveTarget
= true;
455 // ask the application to create a log target for us
456 if ( wxTheApp
!= NULL
)
457 ms_pLogger
= wxTheApp
->GetTraits()->CreateLogTarget();
459 ms_pLogger
= new wxLogStderr
;
461 s_bInGetActiveTarget
= false;
463 // do nothing if it fails - what can we do?
470 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
472 if ( ms_pLogger
!= NULL
) {
473 // flush the old messages before changing because otherwise they might
474 // get lost later if this target is not restored
478 wxLog
*pOldLogger
= ms_pLogger
;
479 ms_pLogger
= pLogger
;
484 void wxLog::DontCreateOnDemand()
486 ms_bAutoCreate
= false;
488 // this is usually called at the end of the program and we assume that it
489 // is *always* called at the end - so we free memory here to avoid false
490 // memory leak reports from wxWin memory tracking code
494 void wxLog::DoCreateOnDemand()
496 ms_bAutoCreate
= true;
499 // ----------------------------------------------------------------------------
500 // wxLog components levels
501 // ----------------------------------------------------------------------------
504 void wxLog::SetComponentLevel(const wxString
& component
, wxLogLevel level
)
506 if ( component
.empty() )
512 wxCRIT_SECT_LOCKER(lock
, GetLevelsCS());
514 gs_componentLevels
[component
] = level
;
519 wxLogLevel
wxLog::GetComponentLevel(wxString component
)
521 wxCRIT_SECT_LOCKER(lock
, GetLevelsCS());
523 while ( !component
.empty() )
525 wxStringToNumHashMap::const_iterator
526 it
= gs_componentLevels
.find(component
);
527 if ( it
!= gs_componentLevels
.end() )
528 return static_cast<wxLogLevel
>(it
->second
);
530 component
= component
.BeforeLast('/');
533 return GetLogLevel();
536 // ----------------------------------------------------------------------------
538 // ----------------------------------------------------------------------------
540 void wxLog::AddTraceMask(const wxString
& str
)
542 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
544 ms_aTraceMasks
.push_back(str
);
547 void wxLog::RemoveTraceMask(const wxString
& str
)
549 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
551 int index
= ms_aTraceMasks
.Index(str
);
552 if ( index
!= wxNOT_FOUND
)
553 ms_aTraceMasks
.RemoveAt((size_t)index
);
556 void wxLog::ClearTraceMasks()
558 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
560 ms_aTraceMasks
.Clear();
563 /*static*/ bool wxLog::IsAllowedTraceMask(const wxString
& mask
)
565 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
567 for ( wxArrayString::iterator it
= ms_aTraceMasks
.begin(),
568 en
= ms_aTraceMasks
.end();
578 // ----------------------------------------------------------------------------
579 // wxLog miscellaneous other methods
580 // ----------------------------------------------------------------------------
582 void wxLog::TimeStamp(wxString
*str
)
585 if ( !ms_timestamp
.empty() )
589 (void)time(&timeNow
);
592 wxStrftime(buf
, WXSIZEOF(buf
),
593 ms_timestamp
, wxLocaltime_r(&timeNow
, &tm
));
596 *str
<< buf
<< wxS(": ");
598 #endif // wxUSE_DATETIME
604 wxASSERT_MSG( wxThread::IsMain(),
605 "should be called from the main thread only" );
607 // check if we have queued messages from other threads
608 wxLogRecords bufferedLogRecords
;
611 wxCriticalSectionLocker
lock(GetBackgroundLogCS());
612 bufferedLogRecords
.swap(gs_bufferedLogRecords
);
614 // release the lock now to not keep it while we are logging the
615 // messages below, allowing background threads to run
618 if ( !bufferedLogRecords
.empty() )
620 for ( wxLogRecords::const_iterator it
= bufferedLogRecords
.begin();
621 it
!= bufferedLogRecords
.end();
624 OnLogInMainThread(it
->level
, it
->msg
, it
->info
);
627 #endif // wxUSE_THREADS
629 LogLastRepeatIfNeeded();
632 // ----------------------------------------------------------------------------
633 // wxLogBuffer implementation
634 // ----------------------------------------------------------------------------
636 void wxLogBuffer::Flush()
640 if ( !m_str
.empty() )
642 wxMessageOutputBest out
;
643 out
.Printf(wxS("%s"), m_str
.c_str());
648 void wxLogBuffer::DoLogTextAtLevel(wxLogLevel level
, const wxString
& msg
)
650 // don't put debug messages in the buffer, we don't want to show
651 // them to the user in a msg box, log them immediately
656 wxLog::DoLogTextAtLevel(level
, msg
);
660 m_str
<< msg
<< wxS("\n");
664 // ----------------------------------------------------------------------------
665 // wxLogStderr class implementation
666 // ----------------------------------------------------------------------------
668 wxLogStderr::wxLogStderr(FILE *fp
)
676 void wxLogStderr::DoLogText(const wxString
& msg
)
678 wxFputs(msg
+ '\n', m_fp
);
681 // under GUI systems such as Windows or Mac, programs usually don't have
682 // stderr at all, so show the messages also somewhere else, typically in
683 // the debugger window so that they go at least somewhere instead of being
685 if ( m_fp
== stderr
)
687 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
688 if ( traits
&& !traits
->HasStderr() )
690 wxMessageOutputDebug().Output(msg
+ wxS('\n'));
695 // ----------------------------------------------------------------------------
696 // wxLogStream implementation
697 // ----------------------------------------------------------------------------
699 #if wxUSE_STD_IOSTREAM
700 #include "wx/ioswrap.h"
701 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
704 m_ostr
= &wxSTD cerr
;
709 void wxLogStream::DoLogText(const wxString
& msg
)
711 (*m_ostr
) << msg
<< wxSTD endl
;
713 #endif // wxUSE_STD_IOSTREAM
715 // ----------------------------------------------------------------------------
717 // ----------------------------------------------------------------------------
719 wxLogChain::wxLogChain(wxLog
*logger
)
721 m_bPassMessages
= true;
724 m_logOld
= wxLog::SetActiveTarget(this);
727 wxLogChain::~wxLogChain()
731 if ( m_logNew
!= this )
735 void wxLogChain::SetLog(wxLog
*logger
)
737 if ( m_logNew
!= this )
743 void wxLogChain::Flush()
748 // be careful to avoid infinite recursion
749 if ( m_logNew
&& m_logNew
!= this )
753 void wxLogChain::DoLogRecord(wxLogLevel level
,
755 const wxLogRecordInfo
& info
)
757 // let the previous logger show it
758 if ( m_logOld
&& IsPassingMessages() )
759 m_logOld
->LogRecord(level
, msg
, info
);
761 // and also send it to the new one
762 if ( m_logNew
&& m_logNew
!= this )
763 m_logNew
->LogRecord(level
, msg
, info
);
767 // "'this' : used in base member initializer list" - so what?
768 #pragma warning(disable:4355)
771 // ----------------------------------------------------------------------------
773 // ----------------------------------------------------------------------------
775 wxLogInterposer::wxLogInterposer()
780 // ----------------------------------------------------------------------------
781 // wxLogInterposerTemp
782 // ----------------------------------------------------------------------------
784 wxLogInterposerTemp::wxLogInterposerTemp()
791 #pragma warning(default:4355)
794 // ============================================================================
795 // Global functions/variables
796 // ============================================================================
798 // ----------------------------------------------------------------------------
800 // ----------------------------------------------------------------------------
802 bool wxLog::ms_bRepetCounting
= false;
804 wxLog
*wxLog::ms_pLogger
= NULL
;
805 bool wxLog::ms_doLog
= true;
806 bool wxLog::ms_bAutoCreate
= true;
807 bool wxLog::ms_bVerbose
= false;
809 wxLogLevel
wxLog::ms_logLevel
= wxLOG_Max
; // log everything by default
811 size_t wxLog::ms_suspendCount
= 0;
813 wxString
wxLog::ms_timestamp(wxS("%X")); // time only, no date
815 #if WXWIN_COMPATIBILITY_2_8
816 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
817 #endif // wxDEBUG_LEVEL
819 wxArrayString
wxLog::ms_aTraceMasks
;
821 // ----------------------------------------------------------------------------
822 // stdout error logging helper
823 // ----------------------------------------------------------------------------
825 // helper function: wraps the message and justifies it under given position
826 // (looks more pretty on the terminal). Also adds newline at the end.
828 // TODO this is now disabled until I find a portable way of determining the
829 // terminal window size (ok, I found it but does anybody really cares?)
830 #ifdef LOG_PRETTY_WRAP
831 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
833 size_t nMax
= 80; // FIXME
834 size_t nStart
= strlen(pszPrefix
);
838 while ( *psz
!= '\0' ) {
839 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
843 if ( *psz
!= '\0' ) {
845 for ( n
= 0; n
< nStart
; n
++ )
848 // as we wrapped, squeeze all white space
849 while ( isspace(*psz
) )
856 #endif //LOG_PRETTY_WRAP
858 // ----------------------------------------------------------------------------
859 // error code/error message retrieval functions
860 // ----------------------------------------------------------------------------
862 // get error code from syste
863 unsigned long wxSysErrorCode()
865 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
866 return ::GetLastError();
872 // get error message from system
873 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
876 nErrCode
= wxSysErrorCode();
878 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
879 static wxChar s_szBuf
[1024];
881 // get error message from system
885 FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
888 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
894 // if this happens, something is seriously wrong, so don't use _() here
896 wxSprintf(s_szBuf
, wxS("unknown error %lx"), nErrCode
);
901 // copy it to our buffer and free memory
902 // Crashes on SmartPhone (FIXME)
903 #if !defined(__SMARTPHONE__) /* of WinCE */
906 wxStrlcpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
));
910 // returned string is capitalized and ended with '\r\n' - bad
911 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
912 size_t len
= wxStrlen(s_szBuf
);
915 if ( s_szBuf
[len
- 2] == wxS('\r') )
916 s_szBuf
[len
- 2] = wxS('\0');
920 #endif // !__SMARTPHONE__
922 s_szBuf
[0] = wxS('\0');
928 static wchar_t s_wzBuf
[1024];
929 wxConvCurrent
->MB2WC(s_wzBuf
, strerror((int)nErrCode
),
930 WXSIZEOF(s_wzBuf
) - 1);
933 return strerror((int)nErrCode
);
935 #endif // __WXMSW__/!__WXMSW__