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"
45 #include "wx/private/threadinfo.h"
47 #include "wx/vector.h"
49 // other standard headers
60 #include "wx/msw/wince/time.h"
62 #endif /* ! __WXPALMOS5__ */
64 #if defined(__WINDOWS__)
65 #include "wx/msw/private.h" // includes windows.h
68 #undef wxLOG_COMPONENT
69 const char *wxLOG_COMPONENT
= "";
73 wxTLS_TYPE(wxThreadSpecificInfo
) wxThreadInfoVar
;
75 // this macro allows to define an object which will be initialized before any
76 // other function in this file is called: this is necessary to allow log
77 // functions to be used during static initialization (this is not advisable
78 // anyhow but we should at least try to not crash) and to also ensure that they
79 // are initialized by the time static initialization is done, i.e. before any
80 // threads are created hopefully
82 // the net effect of all this is that you can use Get##name() function to
83 // access the object without worrying about it being not initialized
85 // see also WX_DEFINE_GLOBAL_CONV2() in src/common/strconv.cpp
86 #define WX_DEFINE_GLOBAL_VAR(type, name) \
87 inline type& Get##name() \
89 static type s_##name; \
93 type *gs_##name##Ptr = &Get##name()
98 // contains messages logged by the other threads and waiting to be shown until
99 // Flush() is called in the main one
100 typedef wxVector
<wxLogRecord
> wxLogRecords
;
101 wxLogRecords gs_bufferedLogRecords
;
103 #define WX_DEFINE_LOG_CS(name) WX_DEFINE_GLOBAL_VAR(wxCriticalSection, name##CS)
105 // this critical section is used for buffering the messages from threads other
106 // than main, i.e. it protects all accesses to gs_bufferedLogRecords above
107 WX_DEFINE_LOG_CS(BackgroundLog
);
109 // this one is used for protecting ms_aTraceMasks from concurrent access
110 WX_DEFINE_LOG_CS(TraceMask
);
112 // and this one is used for GetComponentLevels()
113 WX_DEFINE_LOG_CS(Levels
);
115 } // anonymous namespace
117 #endif // wxUSE_THREADS
119 // ----------------------------------------------------------------------------
120 // non member functions
121 // ----------------------------------------------------------------------------
123 // define this to enable wrapping of log messages
124 //#define LOG_PRETTY_WRAP
126 #ifdef LOG_PRETTY_WRAP
127 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
130 // ----------------------------------------------------------------------------
132 // ----------------------------------------------------------------------------
137 // this struct is used to store information about the previous log message used
138 // by OnLog() to (optionally) avoid logging multiple copies of the same message
139 struct PreviousLogInfo
147 // previous message itself
153 // other information about it
154 wxLogRecordInfo info
;
156 // the number of times it was already repeated
157 unsigned numRepeated
;
160 PreviousLogInfo gs_prevLog
;
163 // map containing all components for which log level was explicitly set
165 // NB: all accesses to it must be protected by GetLevelsCS() critical section
166 WX_DEFINE_GLOBAL_VAR(wxStringToNumHashMap
, ComponentLevels
);
168 } // anonymous namespace
170 // ============================================================================
172 // ============================================================================
174 // ----------------------------------------------------------------------------
175 // helper global functions
176 // ----------------------------------------------------------------------------
178 void wxSafeShowMessage(const wxString
& title
, const wxString
& text
)
181 ::MessageBox(NULL
, text
.t_str(), title
.t_str(), MB_OK
| MB_ICONSTOP
);
183 wxFprintf(stderr
, wxS("%s: %s\n"), title
.c_str(), text
.c_str());
188 // ----------------------------------------------------------------------------
189 // wxLog class implementation
190 // ----------------------------------------------------------------------------
192 unsigned wxLog
::LogLastRepeatIfNeeded()
194 const unsigned count
= gs_prevLog
.numRepeated
;
196 if ( gs_prevLog
.numRepeated
)
200 msg
.Printf(wxPLURAL("The previous message repeated once.",
201 "The previous message repeated %lu times.",
202 gs_prevLog
.numRepeated
),
203 gs_prevLog
.numRepeated
);
205 msg
.Printf(wxS("The previous message was repeated %lu times."),
206 gs_prevLog
.numRepeated
);
208 gs_prevLog
.numRepeated
= 0;
209 gs_prevLog
.msg
.clear();
210 DoLogRecord(gs_prevLog
.level
, msg
, gs_prevLog
.info
);
218 // Flush() must be called before destroying the object as otherwise some
219 // messages could be lost
220 if ( gs_prevLog
.numRepeated
)
222 wxMessageOutputDebug().Printf
224 wxS("Last repeated message (\"%s\", %lu times) wasn't output"),
226 gs_prevLog
.numRepeated
231 // ----------------------------------------------------------------------------
232 // wxLog logging functions
233 // ----------------------------------------------------------------------------
237 wxLog
::OnLog(wxLogLevel level
, const wxString
& msg
, time_t t
)
239 wxLogRecordInfo info
;
242 info
.threadId
= wxThread
::GetCurrentId();
243 #endif // wxUSE_THREADS
245 OnLog(level
, msg
, info
);
250 wxLog
::OnLog(wxLogLevel level
,
252 const wxLogRecordInfo
& info
)
254 // fatal errors can't be suppressed nor handled by the custom log target
255 // and always terminate the program
256 if ( level
== wxLOG_FatalError
)
258 wxSafeShowMessage(wxS("Fatal Error"), msg
);
270 if ( !wxThread
::IsMain() )
272 logger
= wxThreadInfo
.logger
;
277 // buffer the messages until they can be shown from the main
279 wxCriticalSectionLocker
lock(GetBackgroundLogCS());
281 gs_bufferedLogRecords
.push_back(wxLogRecord(level
, msg
, info
));
283 // ensure that our Flush() will be called soon
286 //else: we don't have any logger at all, there is no need to log
291 //else: we have a thread-specific logger, we can send messages to it
295 #endif // wxUSE_THREADS
302 logger
->CallDoLogNow(level
, msg
, info
);
306 wxLog
::CallDoLogNow(wxLogLevel level
,
308 const wxLogRecordInfo
& info
)
310 if ( GetRepetitionCounting() )
312 if ( msg
== gs_prevLog
.msg
)
314 gs_prevLog
.numRepeated
++;
316 // nothing else to do, in particular, don't log the
321 LogLastRepeatIfNeeded();
323 // reset repetition counter for a new message
324 gs_prevLog
.msg
= msg
;
325 gs_prevLog
.level
= level
;
326 gs_prevLog
.info
= info
;
329 // handle extra data which may be passed to us by wxLogXXX()
330 wxString prefix
, suffix
;
332 if ( info
.GetNumValue(wxLOG_KEY_SYS_ERROR_CODE
, &num
) )
334 long err
= static_cast<long>(num
);
336 err
= wxSysErrorCode();
338 suffix
.Printf(_(" (error %ld: %s)"), err
, wxSysErrorMsg(err
));
343 if ( level
== wxLOG_Trace
&& info
.GetStrValue(wxLOG_KEY_TRACE_MASK
, &str
) )
345 prefix
= "(" + str
+ ") ";
347 #endif // wxUSE_LOG_TRACE
349 DoLogRecord(level
, prefix
+ msg
+ suffix
, info
);
352 void wxLog
::DoLogRecord(wxLogLevel level
,
354 const wxLogRecordInfo
& info
)
356 #if WXWIN_COMPATIBILITY_2_8
357 // call the old DoLog() to ensure that existing custom log classes still
360 // as the user code could have defined it as either taking "const char *"
361 // (in ANSI build) or "const wxChar *" (in ANSI/Unicode), we have no choice
362 // but to call both of them
363 DoLog(level
, (const char*)msg
.mb_str(), info
.timestamp
);
364 DoLog(level
, (const wchar_t*)msg
.wc_str(), info
.timestamp
);
365 #endif // WXWIN_COMPATIBILITY_2_8
368 // TODO: it would be better to extract message formatting in a separate
369 // wxLogFormatter class but for now we hard code formatting here
373 // don't time stamp debug messages under MSW as debug viewers usually
374 // already have an option to do it
376 if ( level
!= wxLOG_Debug
&& level
!= wxLOG_Trace
)
380 // TODO: use the other wxLogRecordInfo fields
385 prefix
+= _("Error: ");
389 prefix
+= _("Warning: ");
392 // don't prepend "debug/trace" prefix under MSW as it goes to the debug
393 // window anyhow and so can't be confused with something else
396 // this prefix (as well as the one below) is intentionally not
397 // translated as nobody translates debug messages anyhow
407 DoLogTextAtLevel(level
, prefix
+ msg
);
410 void wxLog
::DoLogTextAtLevel(wxLogLevel level
, const wxString
& msg
)
412 // we know about debug messages (because using wxMessageOutputDebug is the
413 // right thing to do in 99% of all cases and also for compatibility) but
414 // anything else needs to be handled in the derived class
415 if ( level
== wxLOG_Debug
|| level
== wxLOG_Trace
)
417 wxMessageOutputDebug().Output(msg
+ wxS('\n'));
425 void wxLog
::DoLogText(const wxString
& WXUNUSED(msg
))
427 // in 2.8-compatible build the derived class might override DoLog() or
428 // DoLogString() instead so we can't have this assert there
429 #if !WXWIN_COMPATIBILITY_2_8
430 wxFAIL_MSG( "must be overridden if it is called" );
431 #endif // WXWIN_COMPATIBILITY_2_8
434 #if WXWIN_COMPATIBILITY_2_8
436 void wxLog
::DoLog(wxLogLevel
WXUNUSED(level
), const char *szString
, time_t t
)
438 DoLogString(szString
, t
);
441 void wxLog
::DoLog(wxLogLevel
WXUNUSED(level
), const wchar_t *wzString
, time_t t
)
443 DoLogString(wzString
, t
);
446 #endif // WXWIN_COMPATIBILITY_2_8
448 // ----------------------------------------------------------------------------
449 // wxLog active target management
450 // ----------------------------------------------------------------------------
452 wxLog
*wxLog
::GetActiveTarget()
455 if ( !wxThread
::IsMain() )
457 // check if we have a thread-specific log target
458 wxLog
* const logger
= wxThreadInfo
.logger
;
460 // the code below should be only executed for the main thread as
461 // CreateLogTarget() is not meant for auto-creating log targets for
462 // worker threads so skip it in any case
463 return logger ? logger
: ms_pLogger
;
465 #endif // wxUSE_THREADS
467 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
468 // prevent infinite recursion if someone calls wxLogXXX() from
469 // wxApp::CreateLogTarget()
470 static bool s_bInGetActiveTarget
= false;
471 if ( !s_bInGetActiveTarget
) {
472 s_bInGetActiveTarget
= true;
474 // ask the application to create a log target for us
475 if ( wxTheApp
!= NULL
)
476 ms_pLogger
= wxTheApp
->GetTraits()->CreateLogTarget();
478 ms_pLogger
= new wxLogStderr
;
480 s_bInGetActiveTarget
= false;
482 // do nothing if it fails - what can we do?
489 wxLog
*wxLog
::SetActiveTarget(wxLog
*pLogger
)
491 if ( ms_pLogger
!= NULL
) {
492 // flush the old messages before changing because otherwise they might
493 // get lost later if this target is not restored
497 wxLog
*pOldLogger
= ms_pLogger
;
498 ms_pLogger
= pLogger
;
505 wxLog
*wxLog
::SetThreadActiveTarget(wxLog
*logger
)
507 wxASSERT_MSG( !wxThread
::IsMain(), "use SetActiveTarget() for main thread" );
509 wxLog
* const oldLogger
= wxThreadInfo
.logger
;
513 wxThreadInfo
.logger
= logger
;
517 #endif // wxUSE_THREADS
519 void wxLog
::DontCreateOnDemand()
521 ms_bAutoCreate
= false;
523 // this is usually called at the end of the program and we assume that it
524 // is *always* called at the end - so we free memory here to avoid false
525 // memory leak reports from wxWin memory tracking code
529 void wxLog
::DoCreateOnDemand()
531 ms_bAutoCreate
= true;
534 // ----------------------------------------------------------------------------
535 // wxLog components levels
536 // ----------------------------------------------------------------------------
539 void wxLog
::SetComponentLevel(const wxString
& component
, wxLogLevel level
)
541 if ( component
.empty() )
547 wxCRIT_SECT_LOCKER(lock
, GetLevelsCS());
549 GetComponentLevels()[component
] = level
;
554 wxLogLevel wxLog
::GetComponentLevel(wxString component
)
556 wxCRIT_SECT_LOCKER(lock
, GetLevelsCS());
558 const wxStringToNumHashMap
& componentLevels
= GetComponentLevels();
559 while ( !component
.empty() )
561 wxStringToNumHashMap
::const_iterator
562 it
= componentLevels
.find(component
);
563 if ( it
!= componentLevels
.end() )
564 return static_cast<wxLogLevel
>(it
->second
);
566 component
= component
.BeforeLast('/');
569 return GetLogLevel();
572 // ----------------------------------------------------------------------------
574 // ----------------------------------------------------------------------------
576 void wxLog
::AddTraceMask(const wxString
& str
)
578 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
580 ms_aTraceMasks
.push_back(str
);
583 void wxLog
::RemoveTraceMask(const wxString
& str
)
585 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
587 int index
= ms_aTraceMasks
.Index(str
);
588 if ( index
!= wxNOT_FOUND
)
589 ms_aTraceMasks
.RemoveAt((size_t)index
);
592 void wxLog
::ClearTraceMasks()
594 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
596 ms_aTraceMasks
.Clear();
599 /*static*/ bool wxLog
::IsAllowedTraceMask(const wxString
& mask
)
601 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
603 for ( wxArrayString
::iterator it
= ms_aTraceMasks
.begin(),
604 en
= ms_aTraceMasks
.end();
614 // ----------------------------------------------------------------------------
615 // wxLog miscellaneous other methods
616 // ----------------------------------------------------------------------------
618 void wxLog
::TimeStamp(wxString
*str
)
621 if ( !ms_timestamp
.empty() )
625 (void)time(&timeNow
);
628 wxStrftime(buf
, WXSIZEOF(buf
),
629 ms_timestamp
, wxLocaltime_r(&timeNow
, &tm
));
632 *str
<< buf
<< wxS(": ");
634 #endif // wxUSE_DATETIME
639 void wxLog
::FlushThreadMessages()
641 // check if we have queued messages from other threads
642 wxLogRecords bufferedLogRecords
;
645 wxCriticalSectionLocker
lock(GetBackgroundLogCS());
646 bufferedLogRecords
.swap(gs_bufferedLogRecords
);
648 // release the lock now to not keep it while we are logging the
649 // messages below, allowing background threads to run
652 if ( !bufferedLogRecords
.empty() )
654 for ( wxLogRecords
::const_iterator it
= bufferedLogRecords
.begin();
655 it
!= bufferedLogRecords
.end();
658 CallDoLogNow(it
->level
, it
->msg
, it
->info
);
664 bool wxLog
::IsThreadLoggingEnabled()
666 return !wxThreadInfo
.loggingDisabled
;
670 bool wxLog
::EnableThreadLogging(bool enable
)
672 const bool wasEnabled
= !wxThreadInfo
.loggingDisabled
;
673 wxThreadInfo
.loggingDisabled
= !enable
;
677 #endif // wxUSE_THREADS
681 LogLastRepeatIfNeeded();
685 void wxLog
::FlushActive()
687 if ( ms_suspendCount
)
690 wxLog
* const log
= GetActiveTarget();
694 if ( wxThread
::IsMain() )
695 log
->FlushThreadMessages();
696 #endif // wxUSE_THREADS
702 // ----------------------------------------------------------------------------
703 // wxLogBuffer implementation
704 // ----------------------------------------------------------------------------
706 void wxLogBuffer
::Flush()
710 if ( !m_str
.empty() )
712 wxMessageOutputBest out
;
713 out
.Printf(wxS("%s"), m_str
.c_str());
718 void wxLogBuffer
::DoLogTextAtLevel(wxLogLevel level
, const wxString
& msg
)
720 // don't put debug messages in the buffer, we don't want to show
721 // them to the user in a msg box, log them immediately
726 wxLog
::DoLogTextAtLevel(level
, msg
);
730 m_str
<< msg
<< wxS("\n");
734 // ----------------------------------------------------------------------------
735 // wxLogStderr class implementation
736 // ----------------------------------------------------------------------------
738 wxLogStderr
::wxLogStderr(FILE *fp
)
746 void wxLogStderr
::DoLogText(const wxString
& msg
)
748 wxFputs(msg
+ '\n', m_fp
);
751 // under GUI systems such as Windows or Mac, programs usually don't have
752 // stderr at all, so show the messages also somewhere else, typically in
753 // the debugger window so that they go at least somewhere instead of being
755 if ( m_fp
== stderr
)
757 wxAppTraits
*traits
= wxTheApp ? wxTheApp
->GetTraits() : NULL
;
758 if ( traits
&& !traits
->HasStderr() )
760 wxMessageOutputDebug().Output(msg
+ wxS('\n'));
765 // ----------------------------------------------------------------------------
766 // wxLogStream implementation
767 // ----------------------------------------------------------------------------
769 #if wxUSE_STD_IOSTREAM
770 #include "wx/ioswrap.h"
771 wxLogStream
::wxLogStream(wxSTD ostream
*ostr
)
774 m_ostr
= &wxSTD cerr
;
779 void wxLogStream
::DoLogText(const wxString
& msg
)
781 (*m_ostr
) << msg
<< wxSTD endl
;
783 #endif // wxUSE_STD_IOSTREAM
785 // ----------------------------------------------------------------------------
787 // ----------------------------------------------------------------------------
789 wxLogChain
::wxLogChain(wxLog
*logger
)
791 m_bPassMessages
= true;
794 m_logOld
= wxLog
::SetActiveTarget(this);
797 wxLogChain
::~wxLogChain()
801 if ( m_logNew
!= this )
805 void wxLogChain
::SetLog(wxLog
*logger
)
807 if ( m_logNew
!= this )
813 void wxLogChain
::Flush()
818 // be careful to avoid infinite recursion
819 if ( m_logNew
&& m_logNew
!= this )
823 void wxLogChain
::DoLogRecord(wxLogLevel level
,
825 const wxLogRecordInfo
& info
)
827 // let the previous logger show it
828 if ( m_logOld
&& IsPassingMessages() )
829 m_logOld
->LogRecord(level
, msg
, info
);
831 // and also send it to the new one
832 if ( m_logNew
&& m_logNew
!= this )
833 m_logNew
->LogRecord(level
, msg
, info
);
837 // "'this' : used in base member initializer list" - so what?
838 #pragma warning(disable:4355)
841 // ----------------------------------------------------------------------------
843 // ----------------------------------------------------------------------------
845 wxLogInterposer
::wxLogInterposer()
850 // ----------------------------------------------------------------------------
851 // wxLogInterposerTemp
852 // ----------------------------------------------------------------------------
854 wxLogInterposerTemp
::wxLogInterposerTemp()
861 #pragma warning(default:4355)
864 // ============================================================================
865 // Global functions/variables
866 // ============================================================================
868 // ----------------------------------------------------------------------------
870 // ----------------------------------------------------------------------------
872 bool wxLog
::ms_bRepetCounting
= false;
874 wxLog
*wxLog
::ms_pLogger
= NULL
;
875 bool wxLog
::ms_doLog
= true;
876 bool wxLog
::ms_bAutoCreate
= true;
877 bool wxLog
::ms_bVerbose
= false;
879 wxLogLevel wxLog
::ms_logLevel
= wxLOG_Max
; // log everything by default
881 size_t wxLog
::ms_suspendCount
= 0;
883 wxString wxLog
::ms_timestamp(wxS("%X")); // time only, no date
885 #if WXWIN_COMPATIBILITY_2_8
886 wxTraceMask wxLog
::ms_ulTraceMask
= (wxTraceMask
)0;
887 #endif // wxDEBUG_LEVEL
889 wxArrayString wxLog
::ms_aTraceMasks
;
891 // ----------------------------------------------------------------------------
892 // stdout error logging helper
893 // ----------------------------------------------------------------------------
895 // helper function: wraps the message and justifies it under given position
896 // (looks more pretty on the terminal). Also adds newline at the end.
898 // TODO this is now disabled until I find a portable way of determining the
899 // terminal window size (ok, I found it but does anybody really cares?)
900 #ifdef LOG_PRETTY_WRAP
901 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
903 size_t nMax
= 80; // FIXME
904 size_t nStart
= strlen(pszPrefix
);
908 while ( *psz
!= '\0' ) {
909 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
913 if ( *psz
!= '\0' ) {
915 for ( n
= 0; n
< nStart
; n
++ )
918 // as we wrapped, squeeze all white space
919 while ( isspace(*psz
) )
926 #endif //LOG_PRETTY_WRAP
928 // ----------------------------------------------------------------------------
929 // error code/error message retrieval functions
930 // ----------------------------------------------------------------------------
932 // get error code from syste
933 unsigned long wxSysErrorCode()
935 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
936 return ::GetLastError();
942 // get error message from system
943 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
946 nErrCode
= wxSysErrorCode();
948 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
949 static wxChar s_szBuf
[1024];
951 // get error message from system
955 FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
958 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
964 // if this happens, something is seriously wrong, so don't use _() here
966 wxSprintf(s_szBuf
, wxS("unknown error %lx"), nErrCode
);
971 // copy it to our buffer and free memory
972 // Crashes on SmartPhone (FIXME)
973 #if !defined(__SMARTPHONE__) /* of WinCE */
976 wxStrlcpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
));
980 // returned string is capitalized and ended with '\r\n' - bad
981 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
982 size_t len
= wxStrlen(s_szBuf
);
985 if ( s_szBuf
[len
- 2] == wxS('\r') )
986 s_szBuf
[len
- 2] = wxS('\0');
990 #endif // !__SMARTPHONE__
992 s_szBuf
[0] = wxS('\0');
998 static wchar_t s_wzBuf
[1024];
999 wxConvCurrent
->MB2WC(s_wzBuf
, strerror((int)nErrCode
),
1000 WXSIZEOF(s_wzBuf
) - 1);
1003 return strerror((int)nErrCode
);
1005 #endif // __WXMSW__/!__WXMSW__