1 /////////////////////////////////////////////////////////////////////////////
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 license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 #pragma implementation "log.h"
23 // For compilers that support precompilation, includes "wx.h".
24 #include "wx/wxprec.h"
34 #include <wx/string.h>
38 #include <wx/msgdlg.h>
39 #include <wx/filedlg.h>
40 #include <wx/textctrl.h>
44 #include <wx/textfile.h>
48 // other standard headers
55 // Redefines OutputDebugString if necessary
56 #include "wx/msw/private.h"
61 // ----------------------------------------------------------------------------
62 // non member functions
63 // ----------------------------------------------------------------------------
65 // define this to enable wrapping of log messages
66 //#define LOG_PRETTY_WRAP
68 #ifdef LOG_PRETTY_WRAP
69 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
);
72 // ----------------------------------------------------------------------------
74 // ----------------------------------------------------------------------------
76 // we use a global variable to store the frame pointer for wxLogStatus - bad,
77 // but it's he easiest way
78 static wxFrame
*gs_pFrame
;
80 // ============================================================================
82 // ============================================================================
84 // ----------------------------------------------------------------------------
85 // implementation of Log functions
87 // NB: unfortunately we need all these distinct functions, we can't make them
88 // macros and not all compilers inline vararg functions.
89 // ----------------------------------------------------------------------------
91 // log functions can't allocate memory (LogError("out of memory...") should
92 // work!), so we use a static buffer for all log messages
93 #define LOG_BUFFER_SIZE (4096)
95 // static buffer for error messages (@@@ MT-unsafe)
96 static char s_szBuf
[LOG_BUFFER_SIZE
];
98 // generic log function
99 void wxLogGeneric(wxLogLevel level
, const char *szFormat
, ...)
101 if ( wxLog::GetActiveTarget() != NULL
) {
103 va_start(argptr
, szFormat
);
104 vsprintf(s_szBuf
, szFormat
, argptr
);
107 wxLog::OnLog(level
, s_szBuf
);
111 #define IMPLEMENT_LOG_FUNCTION(level) \
112 void wxLog##level(const char *szFormat, ...) \
114 if ( wxLog::GetActiveTarget() != NULL ) { \
116 va_start(argptr, szFormat); \
117 vsprintf(s_szBuf, szFormat, argptr); \
120 wxLog::OnLog(wxLOG_##level, s_szBuf); \
124 IMPLEMENT_LOG_FUNCTION(FatalError
)
125 IMPLEMENT_LOG_FUNCTION(Error
)
126 IMPLEMENT_LOG_FUNCTION(Warning
)
127 IMPLEMENT_LOG_FUNCTION(Message
)
128 IMPLEMENT_LOG_FUNCTION(Info
)
129 IMPLEMENT_LOG_FUNCTION(Status
)
131 // accepts an additional argument which tells to which frame the output should
133 void wxLogStatus(wxFrame
*pFrame
, const char *szFormat
, ...)
135 wxLog
*pLog
= wxLog::GetActiveTarget();
136 if ( pLog
!= NULL
) {
138 va_start(argptr
, szFormat
);
139 vsprintf(s_szBuf
, szFormat
, argptr
);
142 wxASSERT( gs_pFrame
== NULL
); // should be reset!
144 wxLog::OnLog(wxLOG_Status
, s_szBuf
);
145 gs_pFrame
= (wxFrame
*) NULL
;
149 // same as info, but only if 'verbose' mode is on
150 void wxLogVerbose(const char *szFormat
, ...)
152 wxLog
*pLog
= wxLog::GetActiveTarget();
153 if ( pLog
!= NULL
&& pLog
->GetVerbose() ) {
155 va_start(argptr
, szFormat
);
156 vsprintf(s_szBuf
, szFormat
, argptr
);
159 wxLog::OnLog(wxLOG_Info
, s_szBuf
);
165 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
166 void wxLog##level(const char *szFormat, ...) \
168 if ( wxLog::GetActiveTarget() != NULL ) { \
170 va_start(argptr, szFormat); \
171 vsprintf(s_szBuf, szFormat, argptr); \
174 wxLog::OnLog(wxLOG_##level, s_szBuf); \
178 void wxLogTrace(wxTraceMask mask
, const char *szFormat
, ...)
180 wxLog
*pLog
= wxLog::GetActiveTarget();
182 // we check that all of mask bits are set in the current mask, so
183 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
184 // if both bits are set.
185 if ( pLog
!= NULL
&& ((pLog
->GetTraceMask() & mask
) == mask
) ) {
187 va_start(argptr
, szFormat
);
188 vsprintf(s_szBuf
, szFormat
, argptr
);
191 wxLog::OnLog(wxLOG_Trace
, s_szBuf
);
196 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
199 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug
)
200 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace
)
202 // wxLogSysError: one uses the last error code, for other you must give it
205 // common part of both wxLogSysError
206 void wxLogSysErrorHelper(long lErrCode
)
208 char szErrMsg
[LOG_BUFFER_SIZE
/ 2];
209 sprintf(szErrMsg
, _(" (error %ld: %s)"), lErrCode
, wxSysErrorMsg(lErrCode
));
210 strncat(s_szBuf
, szErrMsg
, WXSIZEOF(s_szBuf
) - strlen(s_szBuf
));
212 wxLog::OnLog(wxLOG_Error
, s_szBuf
);
215 void WXDLLEXPORT
wxLogSysError(const char *szFormat
, ...)
218 va_start(argptr
, szFormat
);
219 vsprintf(s_szBuf
, szFormat
, argptr
);
222 wxLogSysErrorHelper(wxSysErrorCode());
225 void WXDLLEXPORT
wxLogSysError(long lErrCode
, const char *szFormat
, ...)
228 va_start(argptr
, szFormat
);
229 vsprintf(s_szBuf
, szFormat
, argptr
);
232 wxLogSysErrorHelper(lErrCode
);
235 // ----------------------------------------------------------------------------
236 // wxLog class implementation
237 // ----------------------------------------------------------------------------
241 m_bHasMessages
= FALSE
;
243 m_szTimeFormat
= "[%d/%b/%y %H:%M:%S] ";
246 wxLog
*wxLog::GetActiveTarget()
248 if ( ms_bAutoCreate
&& ms_pLogger
== NULL
) {
249 // prevent infinite recursion if someone calls wxLogXXX() from
250 // wxApp::CreateLogTarget()
251 static bool s_bInGetActiveTarget
= FALSE
;
252 if ( !s_bInGetActiveTarget
) {
253 s_bInGetActiveTarget
= TRUE
;
256 ms_pLogger
= new wxLogStderr
;
258 // ask the application to create a log target for us
259 if ( wxTheApp
!= NULL
)
260 ms_pLogger
= wxTheApp
->CreateLogTarget();
262 ms_pLogger
= new wxLogStderr
;
265 s_bInGetActiveTarget
= FALSE
;
267 // do nothing if it fails - what can we do?
274 wxLog
*wxLog::SetActiveTarget(wxLog
*pLogger
)
276 if ( ms_pLogger
!= NULL
) {
277 // flush the old messages before changing because otherwise they might
278 // get lost later if this target is not restored
282 wxLog
*pOldLogger
= ms_pLogger
;
283 ms_pLogger
= pLogger
;
288 wxString
wxLog::TimeStamp() const
292 /* Let's disable TimeStamp and see if anyone complains.
293 * If not, we'll remove it, since it's probably unlikely
294 * to ever be used. -- JACS 22/11/98
295 if ( !IsEmpty(m_szTimeFormat) ) {
301 ptmNow = localtime(&timeNow);
303 strftime(szBuf, WXSIZEOF(szBuf), m_szTimeFormat, ptmNow);
311 void wxLog::DoLog(wxLogLevel level
, const char *szString
)
313 // prepend a timestamp if not disabled
314 wxString str
= TimeStamp();
317 case wxLOG_FatalError
:
318 DoLogString(str
<< _("Fatal error: ") << szString
);
319 DoLogString(_("Program aborted."));
325 DoLogString(str
<< _("Error: ") << szString
);
329 DoLogString(str
<< _("Warning: ") << szString
);
335 DoLogString(str
+ szString
);
345 // DoLogString(str << (level == wxLOG_Trace ? _("Trace") : _("Debug"))
346 // << ": " << szString);
347 // JACS: we don't really want to prefix with 'Debug'. It's just extra
349 DoLogString(szString
);
355 wxFAIL_MSG(_("unknown log level in wxLog::DoLog"));
359 void wxLog::DoLogString(const char *WXUNUSED(szString
))
361 wxFAIL_MSG(_("DoLogString must be overrided if it's called."));
369 // ----------------------------------------------------------------------------
370 // wxLogStderr class implementation
371 // ----------------------------------------------------------------------------
373 wxLogStderr::wxLogStderr(FILE *fp
)
381 void wxLogStderr::DoLogString(const char *szString
)
383 fputs(szString
, m_fp
);
388 // ----------------------------------------------------------------------------
389 // wxLogStream implementation
390 // ----------------------------------------------------------------------------
392 #if wxUSE_STD_IOSTREAM
393 wxLogStream::wxLogStream(ostream
*ostr
)
401 void wxLogStream::DoLogString(const char *szString
)
403 (*m_ostr
) << szString
<< endl
<< flush
;
409 // ----------------------------------------------------------------------------
410 // wxLogTextCtrl implementation
411 // ----------------------------------------------------------------------------
413 #if wxUSE_STD_IOSTREAM
414 wxLogTextCtrl::wxLogTextCtrl(wxTextCtrl
*pTextCtrl
)
415 // DLL mode in wxMSW, can't use it.
416 #if defined(NO_TEXT_WINDOW_STREAM)
418 : wxLogStream(new ostream(pTextCtrl
))
423 wxLogTextCtrl::~wxLogTextCtrl()
429 // ----------------------------------------------------------------------------
430 // wxLogGui implementation
431 // ----------------------------------------------------------------------------
438 void wxLogGui::Flush()
440 if ( !m_bHasMessages
)
443 // do it right now to block any new calls to Flush() while we're here
444 m_bHasMessages
= FALSE
;
448 // concatenate all strings (but not too many to not overfill the msg box)
451 nMsgCount
= m_aMessages
.Count();
453 // start from the most recent message
454 for ( size_t n
= nMsgCount
; n
> 0; n
-- ) {
455 // for Windows strings longer than this value are wrapped (NT 4.0)
456 const size_t nMsgLineWidth
= 156;
458 nLines
+= (m_aMessages
[n
- 1].Len() + nMsgLineWidth
- 1) / nMsgLineWidth
;
460 if ( nLines
> 25 ) // don't put too many lines in message box
463 str
<< m_aMessages
[n
- 1] << "\n";
467 wxMessageBox(str
, _("Error"), wxOK
| wxICON_EXCLAMATION
);
470 wxMessageBox(str
, _("Information"), wxOK
| wxICON_INFORMATION
);
473 // no undisplayed messages whatsoever
478 // the default behaviour is to discard all informational messages if there
479 // are any errors/warnings.
480 void wxLogGui::DoLog(wxLogLevel level
, const char *szString
)
487 m_aMessages
.Add(szString
);
488 m_bHasMessages
= TRUE
;
494 // find the top window and set it's status text if it has any
495 wxFrame
*pFrame
= gs_pFrame
;
496 if ( pFrame
== NULL
) {
497 wxWindow
*pWin
= wxTheApp
->GetTopWindow();
498 if ( pWin
!= NULL
&& pWin
->IsKindOf(CLASSINFO(wxFrame
)) ) {
499 pFrame
= (wxFrame
*)pWin
;
503 if ( pFrame
!= NULL
)
504 pFrame
->SetStatusText(szString
);
512 wxString strTime
= TimeStamp();
515 // don't prepend debug/trace here: it goes to the debug window
516 // anyhow, but do put a timestamp
517 OutputDebugString(strTime
+ szString
+ "\n\r");
519 // send them to stderr
521 fprintf(stderr, "%s %s: %s\n",
523 level == wxLOG_Trace ? _("Trace") : _("Debug"),
526 fprintf(stderr
, "%s\n",
534 case wxLOG_FatalError
:
535 // show this one immediately
536 wxMessageBox(szString
, _("Fatal error"), wxICON_HAND
);
541 // discard earlier informational messages if this is the 1st error
544 m_bHasMessages
= TRUE
;
548 m_aMessages
.Add(szString
);
552 wxFAIL_MSG(_("unknown log level in wxLogGui::DoLog"));
556 // ----------------------------------------------------------------------------
557 // wxLogWindow and wxLogFrame implementation
558 // ----------------------------------------------------------------------------
562 class wxLogFrame
: public wxFrame
566 wxLogFrame(wxFrame
*pParent
, wxLogWindow
*log
, const char *szTitle
);
567 virtual ~wxLogFrame();
570 void OnClose(wxCommandEvent
& event
);
571 void OnCloseWindow(wxCloseEvent
& event
);
572 void OnSave (wxCommandEvent
& event
);
573 void OnClear(wxCommandEvent
& event
);
575 void OnIdle(wxIdleEvent
&);
578 wxTextCtrl
*TextCtrl() const { return m_pTextCtrl
; }
588 // instead of closing just hide the window to be able to Show() it later
589 void DoClose() { Show(FALSE
); }
591 wxTextCtrl
*m_pTextCtrl
;
594 DECLARE_EVENT_TABLE()
597 BEGIN_EVENT_TABLE(wxLogFrame
, wxFrame
)
598 // wxLogWindow menu events
599 EVT_MENU(Menu_Close
, wxLogFrame::OnClose
)
600 EVT_MENU(Menu_Save
, wxLogFrame::OnSave
)
601 EVT_MENU(Menu_Clear
, wxLogFrame::OnClear
)
603 EVT_CLOSE(wxLogFrame::OnCloseWindow
)
606 wxLogFrame::wxLogFrame(wxFrame
*pParent
, wxLogWindow
*log
, const char *szTitle
)
607 : wxFrame(pParent
, -1, szTitle
)
611 // @@ kludge: wxSIMPLE_BORDER is simply to prevent wxWindows from creating
612 // a rich edit control instead of a normal one we want in wxMSW
613 m_pTextCtrl
= new wxTextCtrl(this, -1, wxEmptyString
, wxDefaultPosition
,
621 wxMenuBar
*pMenuBar
= new wxMenuBar
;
622 wxMenu
*pMenu
= new wxMenu
;
623 pMenu
->Append(Menu_Save
, _("&Save..."), _("Save log contents to file"));
624 pMenu
->Append(Menu_Clear
, _("C&lear"), _("Clear the log contents"));
625 pMenu
->AppendSeparator();
626 pMenu
->Append(Menu_Close
, _("&Close"), _("Close this window"));
627 pMenuBar
->Append(pMenu
, _("&Log"));
628 SetMenuBar(pMenuBar
);
630 // status bar for menu prompts
633 m_log
->OnFrameCreate(this);
636 void wxLogFrame::OnClose(wxCommandEvent
& WXUNUSED(event
))
641 void wxLogFrame::OnCloseWindow(wxCloseEvent
& WXUNUSED(event
))
646 void wxLogFrame::OnSave(wxCommandEvent
& WXUNUSED(event
))
650 const char *szFileName
= wxSaveFileSelector("log", "txt", "log.txt");
651 if ( szFileName
== NULL
) {
660 if ( wxFile::Exists(szFileName
) ) {
661 bool bAppend
= FALSE
;
663 strMsg
.Printf(_("Append log to file '%s' "
664 "(choosing [No] will overwrite it)?"), szFileName
);
665 switch ( wxMessageBox(strMsg
, _("Question"), wxYES_NO
| wxCANCEL
) ) {
678 wxFAIL_MSG(_("invalid message box return value"));
682 bOk
= file
.Open(szFileName
, wxFile::write_append
);
685 bOk
= file
.Create(szFileName
, TRUE
/* overwrite */);
689 bOk
= file
.Create(szFileName
);
692 // retrieve text and save it
693 // -------------------------
694 int nLines
= m_pTextCtrl
->GetNumberOfLines();
695 for ( int nLine
= 0; bOk
&& nLine
< nLines
; nLine
++ ) {
696 bOk
= file
.Write(m_pTextCtrl
->GetLineText(nLine
) +
697 // we're not going to pull in the whole wxTextFile if all we need is this...
700 #else // !wxUSE_TEXTFILE
702 #endif // wxUSE_TEXTFILE
710 wxLogError(_("Can't save log contents to file."));
713 wxLogStatus(this, _("Log saved to the file '%s'."), szFileName
);
717 void wxLogFrame::OnClear(wxCommandEvent
& WXUNUSED(event
))
719 m_pTextCtrl
->Clear();
722 wxLogFrame::~wxLogFrame()
724 m_log
->OnFrameDelete(this);
729 wxLogWindow::wxLogWindow(wxFrame
*pParent
,
734 m_bPassMessages
= bDoPass
;
736 m_pLogFrame
= new wxLogFrame(pParent
, this, szTitle
);
737 m_pOldLog
= wxLog::SetActiveTarget(this);
740 m_pLogFrame
->Show(TRUE
);
743 void wxLogWindow::Show(bool bShow
)
745 m_pLogFrame
->Show(bShow
);
748 void wxLogWindow::Flush()
750 if ( m_pOldLog
!= NULL
)
753 m_bHasMessages
= FALSE
;
756 void wxLogWindow::DoLog(wxLogLevel level
, const char *szString
)
758 // first let the previous logger show it
759 if ( m_pOldLog
!= NULL
&& m_bPassMessages
) {
760 // @@@ why can't we access protected wxLog method from here (we derive
761 // from wxLog)? gcc gives "DoLog is protected in this context", what
762 // does this mean? Anyhow, the cast is harmless and let's us do what
764 ((wxLogWindow
*)m_pOldLog
)->DoLog(level
, szString
);
770 // by default, these messages are ignored by wxLog, so process
773 wxString str
= TimeStamp();
774 str
<< _("Status: ") << szString
;
779 // don't put trace messages in the text window for 2 reasons:
780 // 1) there are too many of them
781 // 2) they may provoke other trace messages thus sending a program
782 // into an infinite loop
787 // and this will format it nicely and call our DoLogString()
788 wxLog::DoLog(level
, szString
);
792 m_bHasMessages
= TRUE
;
795 void wxLogWindow::DoLogString(const char *szString
)
797 // put the text into our window
798 wxTextCtrl
*pText
= m_pLogFrame
->TextCtrl();
800 // remove selection (WriteText is in fact ReplaceSelection)
802 long nLen
= pText
->GetLastPosition();
803 pText
->SetSelection(nLen
, nLen
);
806 pText
->WriteText(szString
);
807 pText
->WriteText("\n"); // "\n" ok here (_not_ "\r\n")
809 // TODO ensure that the line can be seen
812 wxFrame
*wxLogWindow::GetFrame() const
817 void wxLogWindow::OnFrameCreate(wxFrame
* WXUNUSED(frame
))
821 void wxLogWindow::OnFrameDelete(wxFrame
* WXUNUSED(frame
))
823 m_pLogFrame
= (wxLogFrame
*)NULL
;
826 wxLogWindow::~wxLogWindow()
830 // may be NULL if log frame already auto destroyed itself
836 // ============================================================================
837 // Global functions/variables
838 // ============================================================================
840 // ----------------------------------------------------------------------------
842 // ----------------------------------------------------------------------------
843 wxLog
*wxLog::ms_pLogger
= (wxLog
*) NULL
;
844 bool wxLog::ms_doLog
= TRUE
;
845 bool wxLog::ms_bAutoCreate
= TRUE
;
846 wxTraceMask
wxLog::ms_ulTraceMask
= (wxTraceMask
)0;
848 // ----------------------------------------------------------------------------
849 // stdout error logging helper
850 // ----------------------------------------------------------------------------
852 // helper function: wraps the message and justifies it under given position
853 // (looks more pretty on the terminal). Also adds newline at the end.
855 // @@ this is now disabled until I find a portable way of determining the
856 // terminal window size (ok, I found it but does anybody really cares?)
857 #ifdef LOG_PRETTY_WRAP
858 static void wxLogWrap(FILE *f
, const char *pszPrefix
, const char *psz
)
860 size_t nMax
= 80; // @@@@
861 size_t nStart
= strlen(pszPrefix
);
865 while ( *psz
!= '\0' ) {
866 for ( n
= nStart
; (n
< nMax
) && (*psz
!= '\0'); n
++ )
870 if ( *psz
!= '\0' ) {
872 for ( n
= 0; n
< nStart
; n
++ )
875 // as we wrapped, squeeze all white space
876 while ( isspace(*psz
) )
883 #endif //LOG_PRETTY_WRAP
885 // ----------------------------------------------------------------------------
886 // error code/error message retrieval functions
887 // ----------------------------------------------------------------------------
889 // get error code from syste
890 unsigned long wxSysErrorCode()
894 return ::GetLastError();
896 // @@@@ what to do on Windows 3.1?
904 // get error message from system
905 const char *wxSysErrorMsg(unsigned long nErrCode
)
908 nErrCode
= wxSysErrorCode();
912 static char s_szBuf
[LOG_BUFFER_SIZE
/ 2];
914 // get error message from system
916 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
918 MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
922 // copy it to our buffer and free memory
923 strncpy(s_szBuf
, (const char *)lpMsgBuf
, WXSIZEOF(s_szBuf
) - 1);
924 s_szBuf
[WXSIZEOF(s_szBuf
) - 1] = '\0';
927 // returned string is capitalized and ended with '\r\n' - bad
928 s_szBuf
[0] = (char)wxToLower(s_szBuf
[0]);
929 size_t len
= strlen(s_szBuf
);
932 if ( s_szBuf
[len
- 2] == '\r' )
933 s_szBuf
[len
- 2] = '\0';
942 return strerror(nErrCode
);
946 // ----------------------------------------------------------------------------
948 // ----------------------------------------------------------------------------
956 #elif defined(__WXSTUBS__)
958 #elif defined(__WXMAC__)
969 // this function is called when an assert fails
970 void wxOnAssert(const char *szFile
, int nLine
, const char *szMsg
)
972 // this variable can be set to true to suppress "assert failure" messages
973 static bool s_bNoAsserts
= FALSE
;
974 static bool s_bInAssert
= FALSE
;
977 // He-e-e-e-elp!! we're trapped in endless loop
985 char szBuf
[LOG_BUFFER_SIZE
];
986 sprintf(szBuf
, _("Assert failed in file %s at line %d"), szFile
, nLine
);
987 if ( szMsg
!= NULL
) {
989 strcat(szBuf
, szMsg
);
995 if ( !s_bNoAsserts
) {
996 // send it to the normal log destination
1002 strcat(szBuf
, _("\nDo you want to stop the program?"
1003 "\nYou can also choose [Cancel] to suppress "
1004 "further warnings."));
1006 switch ( wxMessageBox(szBuf
, _("Debug"),
1007 wxYES_NO
| wxCANCEL
| wxICON_STOP
) ) {
1013 s_bNoAsserts
= TRUE
;
1016 //case wxNO: nothing to do
1021 s_bInAssert
= FALSE
;