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"
47 // other standard headers
58 #include "wx/msw/wince/time.h"
60 #endif /* ! __WXPALMOS5__ */
62 #if defined(__WINDOWS__)
63 #include "wx/msw/private.h" // includes windows.h
68 // define static functions providing access to the critical sections we use
69 // instead of just using static critical section variables as log functions may
70 // be used during static initialization and while this is certainly not
71 // advisable it's still better to not crash (as we'd do if we used a yet
72 // uninitialized critical section) if it happens
74 static inline wxCriticalSection
& GetTraceMaskCS()
76 static wxCriticalSection s_csTrace
;
81 static inline wxCriticalSection
& GetPreviousLogCS()
83 static wxCriticalSection s_csPrev
;
88 #endif // wxUSE_THREADS
90 // ----------------------------------------------------------------------------
91 // non member functions
92 // ----------------------------------------------------------------------------
94 // define this to enable wrapping of log messages
95 //#define LOG_PRETTY_WRAP
97 #ifdef LOG_PRETTY_WRAP
98 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
101 // ----------------------------------------------------------------------------
103 // ----------------------------------------------------------------------------
108 // this struct is used to store information about the previous log message used
109 // by OnLog() to (optionally) avoid logging multiple copies of the same message
110 struct PreviousLogInfo
118 // previous message itself
124 // other information about it
125 wxLogRecordInfo info
;
127 // the number of times it was already repeated
128 unsigned numRepeated
;
131 PreviousLogInfo gs_prevLog
;
133 } // anonymous namespace
135 // ============================================================================
137 // ============================================================================
139 // ----------------------------------------------------------------------------
140 // helper global functions
141 // ----------------------------------------------------------------------------
143 void wxSafeShowMessage(const wxString
& title
, const wxString
& text
)
146 ::MessageBox(NULL
, text
.t_str(), title
.t_str(), MB_OK
| MB_ICONSTOP
);
148 wxFprintf(stderr
, wxS("%s: %s\n"), title
.c_str(), text
.c_str());
153 // ----------------------------------------------------------------------------
154 // wxLog class implementation
155 // ----------------------------------------------------------------------------
157 unsigned wxLog::LogLastRepeatIfNeeded()
159 wxCRIT_SECT_LOCKER(lock
, GetPreviousLogCS());
161 return LogLastRepeatIfNeededUnlocked();
164 unsigned wxLog::LogLastRepeatIfNeededUnlocked()
166 const unsigned count
= gs_prevLog
.numRepeated
;
168 if ( gs_prevLog
.numRepeated
)
172 msg
.Printf(wxPLURAL("The previous message repeated once.",
173 "The previous message repeated %lu times.",
174 gs_prevLog
.numRepeated
),
175 gs_prevLog
.numRepeated
);
177 msg
.Printf(wxS("The previous message was repeated %lu times."),
178 gs_prevLog
.numRepeated
);
180 gs_prevLog
.numRepeated
= 0;
181 gs_prevLog
.msg
.clear();
182 DoLogRecord(gs_prevLog
.level
, msg
, gs_prevLog
.info
);
190 // Flush() must be called before destroying the object as otherwise some
191 // messages could be lost
192 if ( gs_prevLog
.numRepeated
)
194 wxMessageOutputDebug().Printf
196 wxS("Last repeated message (\"%s\", %lu times) wasn't output"),
198 gs_prevLog
.numRepeated
203 // ----------------------------------------------------------------------------
204 // wxLog logging functions
205 // ----------------------------------------------------------------------------
209 wxLog::OnLog(wxLogLevel level
, const wxString
& msg
, time_t t
)
211 wxLogRecordInfo info
;
214 info
.threadId
= wxThread::GetCurrentId();
215 #endif // wxUSE_THREADS
217 OnLog(level
, msg
, info
);
222 wxLog::OnLog(wxLogLevel level
,
224 const wxLogRecordInfo
& info
)
226 // fatal errors can't be suppressed nor handled by the custom log target
227 // and always terminate the program
228 if ( level
== wxLOG_FatalError
)
230 wxSafeShowMessage(wxS("Fatal Error"), msg
);
239 wxLog
*pLogger
= GetActiveTarget();
243 if ( GetRepetitionCounting() )
245 wxCRIT_SECT_LOCKER(lock
, GetPreviousLogCS());
247 if ( msg
== gs_prevLog
.msg
)
249 gs_prevLog
.numRepeated
++;
251 // nothing else to do, in particular, don't log the
256 pLogger
->LogLastRepeatIfNeededUnlocked();
258 // reset repetition counter for a new message
259 gs_prevLog
.msg
= msg
;
260 gs_prevLog
.level
= level
;
261 gs_prevLog
.info
= info
;
264 // handle extra data which may be passed to us by wxLogXXX()
265 wxString prefix
, suffix
;
267 if ( info
.GetNumValue(wxLOG_KEY_SYS_ERROR_CODE
, &num
) )
269 long err
= static_cast<long>(num
);
271 err
= wxSysErrorCode();
273 suffix
.Printf(_(" (error %ld: %s)"), err
, wxSysErrorMsg(err
));
278 if ( level
== wxLOG_Trace
&& info
.GetStrValue(wxLOG_KEY_TRACE_MASK
, &str
) )
280 prefix
= "(" + str
+ ") ";
282 #endif // wxUSE_LOG_TRACE
284 pLogger
->DoLogRecord(level
, prefix
+ msg
+ suffix
, info
);
287 void wxLog::DoLogRecord(wxLogLevel level
,
289 const wxLogRecordInfo
& info
)
291 #if WXWIN_COMPATIBILITY_2_8
292 // call the old DoLog() to ensure that existing custom log classes still
295 // as the user code could have defined it as either taking "const char *"
296 // (in ANSI build) or "const wxChar *" (in ANSI/Unicode), we have no choice
297 // but to call both of them
298 DoLog(level
, (const char*)msg
.mb_str(), info
.timestamp
);
299 DoLog(level
, (const wchar_t*)msg
.wc_str(), info
.timestamp
);
300 #endif // WXWIN_COMPATIBILITY_2_8
303 // TODO: it would be better to extract message formatting in a separate
304 // wxLogFormatter class but for now we hard code formatting here
308 // don't time stamp debug messages under MSW as debug viewers usually
309 // already have an option to do it
311 if ( level
!= wxLOG_Debug
&& level
!= wxLOG_Trace
)
315 // TODO: use the other wxLogRecordInfo fields
320 prefix
+= _("Error: ");
324 prefix
+= _("Warning: ");
327 // don't prepend "debug/trace" prefix under MSW as it goes to the debug
328 // window anyhow and so can't be confused with something else
331 // this prefix (as well as the one below) is intentionally not
332 // translated as nobody translates debug messages anyhow
342 DoLogTextAtLevel(level
, prefix
+ msg
);
345 void wxLog::DoLogTextAtLevel(wxLogLevel level
, const wxString
& msg
)
347 // we know about debug messages (because using wxMessageOutputDebug is the
348 // right thing to do in 99% of all cases and also for compatibility) but
349 // anything else needs to be handled in the derived class
350 if ( level
== wxLOG_Debug
|| level
== wxLOG_Trace
)
352 wxMessageOutputDebug().Output(msg
+ wxS('\n'));
360 void wxLog::DoLogText(const wxString
& WXUNUSED(msg
))
362 // in 2.8-compatible build the derived class might override DoLog() or
363 // DoLogString() instead so we can't have this assert there
364 #if !WXWIN_COMPATIBILITY_2_8
365 wxFAIL_MSG( "must be overridden if it is called" );
366 #endif // WXWIN_COMPATIBILITY_2_8
369 #if WXWIN_COMPATIBILITY_2_8
371 void wxLog::DoLog(wxLogLevel
WXUNUSED(level
), const char *szString
, time_t t
)
373 DoLogString(szString
, t
);
376 void wxLog::DoLog(wxLogLevel
WXUNUSED(level
), const wchar_t *wzString
, time_t t
)
378 DoLogString(wzString
, t
);
381 #endif // WXWIN_COMPATIBILITY_2_8
383 // ----------------------------------------------------------------------------
384 // wxLog active target management
385 // ----------------------------------------------------------------------------
387 wxLog
*wxLog::GetActiveTarget()
389 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
390 // prevent infinite recursion if someone calls wxLogXXX() from
391 // wxApp::CreateLogTarget()
392 static bool s_bInGetActiveTarget
= false;
393 if ( !s_bInGetActiveTarget
) {
394 s_bInGetActiveTarget
= true;
396 // ask the application to create a log target for us
397 if ( wxTheApp
!= NULL
)
398 ms_pLogger
= wxTheApp
->GetTraits()->CreateLogTarget();
400 ms_pLogger
= new wxLogStderr
;
402 s_bInGetActiveTarget
= false;
404 // do nothing if it fails - what can we do?
411 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
413 if ( ms_pLogger
!= NULL
) {
414 // flush the old messages before changing because otherwise they might
415 // get lost later if this target is not restored
419 wxLog
*pOldLogger
= ms_pLogger
;
420 ms_pLogger
= pLogger
;
425 void wxLog::DontCreateOnDemand()
427 ms_bAutoCreate
= false;
429 // this is usually called at the end of the program and we assume that it
430 // is *always* called at the end - so we free memory here to avoid false
431 // memory leak reports from wxWin memory tracking code
435 void wxLog::DoCreateOnDemand()
437 ms_bAutoCreate
= true;
440 void wxLog::AddTraceMask(const wxString
& str
)
442 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
444 ms_aTraceMasks
.push_back(str
);
447 void wxLog::RemoveTraceMask(const wxString
& str
)
449 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
451 int index
= ms_aTraceMasks
.Index(str
);
452 if ( index
!= wxNOT_FOUND
)
453 ms_aTraceMasks
.RemoveAt((size_t)index
);
456 void wxLog::ClearTraceMasks()
458 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
460 ms_aTraceMasks
.Clear();
463 void wxLog::TimeStamp(wxString
*str
)
466 if ( !ms_timestamp
.empty() )
470 (void)time(&timeNow
);
473 wxStrftime(buf
, WXSIZEOF(buf
),
474 ms_timestamp
, wxLocaltime_r(&timeNow
, &tm
));
477 *str
<< buf
<< wxS(": ");
479 #endif // wxUSE_DATETIME
484 LogLastRepeatIfNeeded();
487 /*static*/ bool wxLog::IsAllowedTraceMask(const wxString
& mask
)
489 wxCRIT_SECT_LOCKER(lock
, GetTraceMaskCS());
491 for ( wxArrayString::iterator it
= ms_aTraceMasks
.begin(),
492 en
= ms_aTraceMasks
.end();
502 // ----------------------------------------------------------------------------
503 // wxLogBuffer implementation
504 // ----------------------------------------------------------------------------
506 void wxLogBuffer::Flush()
508 if ( !m_str
.empty() )
510 wxMessageOutputBest out
;
511 out
.Printf(wxS("%s"), m_str
.c_str());
516 void wxLogBuffer::DoLogTextAtLevel(wxLogLevel level
, const wxString
& msg
)
518 // don't put debug messages in the buffer, we don't want to show
519 // them to the user in a msg box, log them immediately
524 wxLog::DoLogTextAtLevel(level
, msg
);
528 m_str
<< msg
<< wxS("\n");
532 // ----------------------------------------------------------------------------
533 // wxLogStderr class implementation
534 // ----------------------------------------------------------------------------
536 wxLogStderr::wxLogStderr(FILE *fp
)
544 void wxLogStderr::DoLogText(const wxString
& msg
)
546 wxFputs(msg
+ '\n', m_fp
);
549 // under GUI systems such as Windows or Mac, programs usually don't have
550 // stderr at all, so show the messages also somewhere else, typically in
551 // the debugger window so that they go at least somewhere instead of being
553 if ( m_fp
== stderr
)
555 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
556 if ( traits
&& !traits
->HasStderr() )
558 wxMessageOutputDebug().Output(msg
+ wxS('\n'));
563 // ----------------------------------------------------------------------------
564 // wxLogStream implementation
565 // ----------------------------------------------------------------------------
567 #if wxUSE_STD_IOSTREAM
568 #include "wx/ioswrap.h"
569 wxLogStream::wxLogStream(wxSTD ostream
*ostr
)
572 m_ostr
= &wxSTD cerr
;
577 void wxLogStream::DoLogText(const wxString
& msg
)
579 (*m_ostr
) << msg
<< wxSTD endl
;
581 #endif // wxUSE_STD_IOSTREAM
583 // ----------------------------------------------------------------------------
585 // ----------------------------------------------------------------------------
587 wxLogChain::wxLogChain(wxLog
*logger
)
589 m_bPassMessages
= true;
592 m_logOld
= wxLog::SetActiveTarget(this);
595 wxLogChain::~wxLogChain()
599 if ( m_logNew
!= this )
603 void wxLogChain::SetLog(wxLog
*logger
)
605 if ( m_logNew
!= this )
611 void wxLogChain::Flush()
616 // be careful to avoid infinite recursion
617 if ( m_logNew
&& m_logNew
!= this )
621 void wxLogChain::DoLogRecord(wxLogLevel level
,
623 const wxLogRecordInfo
& info
)
625 // let the previous logger show it
626 if ( m_logOld
&& IsPassingMessages() )
627 m_logOld
->LogRecord(level
, msg
, info
);
629 // and also send it to the new one
630 if ( m_logNew
&& m_logNew
!= this )
631 m_logNew
->LogRecord(level
, msg
, info
);
635 // "'this' : used in base member initializer list" - so what?
636 #pragma warning(disable:4355)
639 // ----------------------------------------------------------------------------
641 // ----------------------------------------------------------------------------
643 wxLogInterposer::wxLogInterposer()
648 // ----------------------------------------------------------------------------
649 // wxLogInterposerTemp
650 // ----------------------------------------------------------------------------
652 wxLogInterposerTemp::wxLogInterposerTemp()
659 #pragma warning(default:4355)
662 // ============================================================================
663 // Global functions/variables
664 // ============================================================================
666 // ----------------------------------------------------------------------------
668 // ----------------------------------------------------------------------------
670 bool wxLog::ms_bRepetCounting
= false;
672 wxLog
*wxLog::ms_pLogger
= NULL
;
673 bool wxLog::ms_doLog
= true;
674 bool wxLog::ms_bAutoCreate
= true;
675 bool wxLog::ms_bVerbose
= false;
677 wxLogLevel
wxLog::ms_logLevel
= wxLOG_Max
; // log everything by default
679 size_t wxLog::ms_suspendCount
= 0;
681 wxString
wxLog::ms_timestamp(wxS("%X")); // time only, no date
683 #if WXWIN_COMPATIBILITY_2_8
684 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
685 #endif // wxDEBUG_LEVEL
687 wxArrayString
wxLog::ms_aTraceMasks
;
689 // ----------------------------------------------------------------------------
690 // stdout error logging helper
691 // ----------------------------------------------------------------------------
693 // helper function: wraps the message and justifies it under given position
694 // (looks more pretty on the terminal). Also adds newline at the end.
696 // TODO this is now disabled until I find a portable way of determining the
697 // terminal window size (ok, I found it but does anybody really cares?)
698 #ifdef LOG_PRETTY_WRAP
699 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
701 size_t nMax
= 80; // FIXME
702 size_t nStart
= strlen(pszPrefix
);
706 while ( *psz
!= '\0' ) {
707 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
711 if ( *psz
!= '\0' ) {
713 for ( n
= 0; n
< nStart
; n
++ )
716 // as we wrapped, squeeze all white space
717 while ( isspace(*psz
) )
724 #endif //LOG_PRETTY_WRAP
726 // ----------------------------------------------------------------------------
727 // error code/error message retrieval functions
728 // ----------------------------------------------------------------------------
730 // get error code from syste
731 unsigned long wxSysErrorCode()
733 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
734 return ::GetLastError();
740 // get error message from system
741 const wxChar
*wxSysErrorMsg(unsigned long nErrCode
)
744 nErrCode
= wxSysErrorCode();
746 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
747 static wxChar s_szBuf
[1024];
749 // get error message from system
753 FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
756 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
762 // if this happens, something is seriously wrong, so don't use _() here
764 wxSprintf(s_szBuf
, wxS("unknown error %lx"), nErrCode
);
769 // copy it to our buffer and free memory
770 // Crashes on SmartPhone (FIXME)
771 #if !defined(__SMARTPHONE__) /* of WinCE */
774 wxStrlcpy(s_szBuf
, (const wxChar
*)lpMsgBuf
, WXSIZEOF(s_szBuf
));
778 // returned string is capitalized and ended with '\r\n' - bad
779 s_szBuf
[0] = (wxChar
)wxTolower(s_szBuf
[0]);
780 size_t len
= wxStrlen(s_szBuf
);
783 if ( s_szBuf
[len
- 2] == wxS('\r') )
784 s_szBuf
[len
- 2] = wxS('\0');
788 #endif // !__SMARTPHONE__
790 s_szBuf
[0] = wxS('\0');
796 static wchar_t s_wzBuf
[1024];
797 wxConvCurrent
->MB2WC(s_wzBuf
, strerror((int)nErrCode
),
798 WXSIZEOF(s_wzBuf
) - 1);
801 return strerror((int)nErrCode
);
803 #endif // __WXMSW__/!__WXMSW__