]> git.saurik.com Git - wxWidgets.git/blob - src/common/log.cpp
Implemented wxStatusBar::Push/PopStatusText.
[wxWidgets.git] / src / common / log.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: log.cpp
3 // Purpose: Assorted wxLogXXX functions, and wxLog (sink for logs)
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 29/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 #pragma implementation "log.h"
22 #endif
23
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 // wxWindows
32 #ifndef WX_PRECOMP
33 #include "wx/string.h"
34 #include "wx/intl.h"
35 #include "wx/app.h"
36
37 #if wxUSE_GUI
38 #include "wx/window.h"
39 #include "wx/msgdlg.h"
40 #ifdef __WXMSW__
41 #include "wx/msw/private.h"
42 #endif
43 #endif
44 #endif //WX_PRECOMP
45
46 #include "wx/file.h"
47 #include "wx/textfile.h"
48 #include "wx/utils.h"
49 #include "wx/wxchar.h"
50 #include "wx/log.h"
51 #include "wx/thread.h"
52
53 #if wxUSE_LOG
54
55 // other standard headers
56 #include <errno.h>
57 #include <stdlib.h>
58 #include <time.h>
59
60 #if defined(__WXMSW__)
61 #include "wx/msw/private.h" // includes windows.h for OutputDebugString
62 #endif
63
64 #if defined(__WXMAC__)
65 #include "wx/mac/private.h" // includes mac headers
66 #endif
67
68 // ----------------------------------------------------------------------------
69 // non member functions
70 // ----------------------------------------------------------------------------
71
72 // define this to enable wrapping of log messages
73 //#define LOG_PRETTY_WRAP
74
75 #ifdef LOG_PRETTY_WRAP
76 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz);
77 #endif
78
79 // ============================================================================
80 // implementation
81 // ============================================================================
82
83 // ----------------------------------------------------------------------------
84 // globals
85 // ----------------------------------------------------------------------------
86
87 // log functions can't allocate memory (LogError("out of memory...") should
88 // work!), so we use a static buffer for all log messages
89 #define LOG_BUFFER_SIZE (4096)
90
91 // static buffer for error messages
92 static wxChar s_szBufStatic[LOG_BUFFER_SIZE];
93
94 static wxChar *s_szBuf = s_szBufStatic;
95 static size_t s_szBufSize = WXSIZEOF( s_szBufStatic );
96
97 #if wxUSE_THREADS
98
99 // the critical section protecting the static buffer
100 static wxCriticalSection gs_csLogBuf;
101
102 #endif // wxUSE_THREADS
103
104 // return true if we have a non NULL non disabled log target
105 static inline bool IsLoggingEnabled()
106 {
107 return wxLog::IsEnabled() && (wxLog::GetActiveTarget() != NULL);
108 }
109
110 // ----------------------------------------------------------------------------
111 // implementation of Log functions
112 //
113 // NB: unfortunately we need all these distinct functions, we can't make them
114 // macros and not all compilers inline vararg functions.
115 // ----------------------------------------------------------------------------
116
117 // generic log function
118 void wxVLogGeneric(wxLogLevel level, const wxChar *szFormat, va_list argptr)
119 {
120 if ( IsLoggingEnabled() ) {
121 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
122
123 wxVsnprintf(s_szBuf, s_szBufSize, szFormat, argptr);
124
125 wxLog::OnLog(level, s_szBuf, time(NULL));
126 }
127 }
128
129 void wxLogGeneric(wxLogLevel level, const wxChar *szFormat, ...)
130 {
131 va_list argptr;
132 va_start(argptr, szFormat);
133 wxVLogGeneric(level, szFormat, argptr);
134 va_end(argptr);
135 }
136
137 #define IMPLEMENT_LOG_FUNCTION(level) \
138 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
139 { \
140 if ( IsLoggingEnabled() ) { \
141 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
142 \
143 wxVsnprintf(s_szBuf, s_szBufSize, szFormat, argptr); \
144 \
145 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
146 } \
147 } \
148 void wxLog##level(const wxChar *szFormat, ...) \
149 { \
150 va_list argptr; \
151 va_start(argptr, szFormat); \
152 wxVLog##level(szFormat, argptr); \
153 va_end(argptr); \
154 }
155
156 IMPLEMENT_LOG_FUNCTION(Error)
157 IMPLEMENT_LOG_FUNCTION(Warning)
158 IMPLEMENT_LOG_FUNCTION(Message)
159 IMPLEMENT_LOG_FUNCTION(Info)
160 IMPLEMENT_LOG_FUNCTION(Status)
161
162 // fatal errors can't be suppressed nor handled by the custom log target and
163 // always terminate the program
164 void wxVLogFatalError(const wxChar *szFormat, va_list argptr)
165 {
166 wxVsnprintf(s_szBuf, s_szBufSize, szFormat, argptr);
167
168 #if wxUSE_GUI
169 wxMessageBox(s_szBuf, _("Fatal Error"), wxID_OK | wxICON_STOP);
170 #else
171 wxFprintf(stderr, _("Fatal error: %s\n"), s_szBuf);
172 #endif
173
174 abort();
175 }
176
177 void wxLogFatalError(const wxChar *szFormat, ...)
178 {
179 va_list argptr;
180 va_start(argptr, szFormat);
181 wxVLogFatalError(szFormat, argptr);
182 va_end(argptr);
183 }
184
185 // same as info, but only if 'verbose' mode is on
186 void wxVLogVerbose(const wxChar *szFormat, va_list argptr)
187 {
188 if ( IsLoggingEnabled() ) {
189 wxLog *pLog = wxLog::GetActiveTarget();
190 if ( pLog != NULL && pLog->GetVerbose() ) {
191 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
192
193 wxVsnprintf(s_szBuf, s_szBufSize, szFormat, argptr);
194
195 wxLog::OnLog(wxLOG_Info, s_szBuf, time(NULL));
196 }
197 }
198 }
199
200 void wxLogVerbose(const wxChar *szFormat, ...)
201 {
202 va_list argptr;
203 va_start(argptr, szFormat);
204 wxVLogVerbose(szFormat, argptr);
205 va_end(argptr);
206 }
207
208 // debug functions
209 #ifdef __WXDEBUG__
210 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level) \
211 void wxVLog##level(const wxChar *szFormat, va_list argptr) \
212 { \
213 if ( IsLoggingEnabled() ) { \
214 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf); \
215 \
216 wxVsnprintf(s_szBuf, s_szBufSize, szFormat, argptr); \
217 \
218 wxLog::OnLog(wxLOG_##level, s_szBuf, time(NULL)); \
219 } \
220 } \
221 void wxLog##level(const wxChar *szFormat, ...) \
222 { \
223 va_list argptr; \
224 va_start(argptr, szFormat); \
225 wxVLog##level(szFormat, argptr); \
226 va_end(argptr); \
227 }
228
229 void wxVLogTrace(const wxChar *mask, const wxChar *szFormat, va_list argptr)
230 {
231 if ( IsLoggingEnabled() && wxLog::IsAllowedTraceMask(mask) ) {
232 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
233
234 wxChar *p = s_szBuf;
235 size_t len = s_szBufSize;
236 wxStrncpy(s_szBuf, _T("("), len);
237 len -= 1; // strlen("(")
238 p += 1;
239 wxStrncat(p, mask, len);
240 size_t lenMask = wxStrlen(mask);
241 len -= lenMask;
242 p += lenMask;
243
244 wxStrncat(p, _T(") "), len);
245 len -= 2;
246 p += 2;
247
248 wxVsnprintf(p, len, szFormat, argptr);
249
250 wxLog::OnLog(wxLOG_Trace, s_szBuf, time(NULL));
251 }
252 }
253
254 void wxLogTrace(const wxChar *mask, const wxChar *szFormat, ...)
255 {
256 va_list argptr;
257 va_start(argptr, szFormat);
258 wxVLogTrace(mask, szFormat, argptr);
259 va_end(argptr);
260 }
261
262 void wxVLogTrace(wxTraceMask mask, const wxChar *szFormat, va_list argptr)
263 {
264 // we check that all of mask bits are set in the current mask, so
265 // that wxLogTrace(wxTraceRefCount | wxTraceOle) will only do something
266 // if both bits are set.
267 if ( IsLoggingEnabled() && ((wxLog::GetTraceMask() & mask) == mask) ) {
268 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
269
270 wxVsnprintf(s_szBuf, s_szBufSize, szFormat, argptr);
271
272 wxLog::OnLog(wxLOG_Trace, s_szBuf, time(NULL));
273 }
274 }
275
276 void wxLogTrace(wxTraceMask mask, const wxChar *szFormat, ...)
277 {
278 va_list argptr;
279 va_start(argptr, szFormat);
280 wxVLogTrace(mask, szFormat, argptr);
281 va_end(argptr);
282 }
283
284 #else // release
285 #define IMPLEMENT_LOG_DEBUG_FUNCTION(level)
286 #endif
287
288 IMPLEMENT_LOG_DEBUG_FUNCTION(Debug)
289 IMPLEMENT_LOG_DEBUG_FUNCTION(Trace)
290
291 // wxLogSysError: one uses the last error code, for other you must give it
292 // explicitly
293
294 // common part of both wxLogSysError
295 void wxLogSysErrorHelper(long lErrCode)
296 {
297 wxChar szErrMsg[LOG_BUFFER_SIZE / 2];
298 wxSnprintf(szErrMsg, WXSIZEOF(szErrMsg),
299 _(" (error %ld: %s)"), lErrCode, wxSysErrorMsg(lErrCode));
300 wxStrncat(s_szBuf, szErrMsg, s_szBufSize - wxStrlen(s_szBuf));
301
302 wxLog::OnLog(wxLOG_Error, s_szBuf, time(NULL));
303 }
304
305 void WXDLLEXPORT wxVLogSysError(const wxChar *szFormat, va_list argptr)
306 {
307 if ( IsLoggingEnabled() ) {
308 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
309
310 wxVsnprintf(s_szBuf, s_szBufSize, szFormat, argptr);
311
312 wxLogSysErrorHelper(wxSysErrorCode());
313 }
314 }
315
316 void WXDLLEXPORT wxLogSysError(const wxChar *szFormat, ...)
317 {
318 va_list argptr;
319 va_start(argptr, szFormat);
320 wxVLogSysError(szFormat, argptr);
321 va_end(argptr);
322 }
323
324 void WXDLLEXPORT wxVLogSysError(long lErrCode, const wxChar *szFormat, va_list argptr)
325 {
326 if ( IsLoggingEnabled() ) {
327 wxCRIT_SECT_LOCKER(locker, gs_csLogBuf);
328
329 wxVsnprintf(s_szBuf, s_szBufSize, szFormat, argptr);
330
331 wxLogSysErrorHelper(lErrCode);
332 }
333 }
334
335 void WXDLLEXPORT wxLogSysError(long lErrCode, const wxChar *szFormat, ...)
336 {
337 va_list argptr;
338 va_start(argptr, szFormat);
339 wxVLogSysError(lErrCode, szFormat, argptr);
340 va_end(argptr);
341 }
342
343 // ----------------------------------------------------------------------------
344 // wxLog class implementation
345 // ----------------------------------------------------------------------------
346
347 wxLog::wxLog()
348 {
349 m_bHasMessages = FALSE;
350 }
351
352 wxChar *wxLog::SetLogBuffer( wxChar *buf, size_t size)
353 {
354 wxChar *oldbuf = s_szBuf;
355
356 if( buf == 0 )
357 {
358 s_szBuf = s_szBufStatic;
359 s_szBufSize = WXSIZEOF( s_szBufStatic );
360 }
361 else
362 {
363 s_szBuf = buf;
364 s_szBufSize = size;
365 }
366
367 return (oldbuf == s_szBufStatic ) ? 0 : oldbuf;
368 }
369
370 wxLog *wxLog::GetActiveTarget()
371 {
372 if ( ms_bAutoCreate && ms_pLogger == NULL ) {
373 // prevent infinite recursion if someone calls wxLogXXX() from
374 // wxApp::CreateLogTarget()
375 static bool s_bInGetActiveTarget = FALSE;
376 if ( !s_bInGetActiveTarget ) {
377 s_bInGetActiveTarget = TRUE;
378
379 // ask the application to create a log target for us
380 if ( wxTheApp != NULL )
381 ms_pLogger = wxTheApp->CreateLogTarget();
382 else
383 ms_pLogger = new wxLogStderr;
384
385 s_bInGetActiveTarget = FALSE;
386
387 // do nothing if it fails - what can we do?
388 }
389 }
390
391 return ms_pLogger;
392 }
393
394 wxLog *wxLog::SetActiveTarget(wxLog *pLogger)
395 {
396 if ( ms_pLogger != NULL ) {
397 // flush the old messages before changing because otherwise they might
398 // get lost later if this target is not restored
399 ms_pLogger->Flush();
400 }
401
402 wxLog *pOldLogger = ms_pLogger;
403 ms_pLogger = pLogger;
404
405 return pOldLogger;
406 }
407
408 void wxLog::DontCreateOnDemand()
409 {
410 ms_bAutoCreate = FALSE;
411
412 // this is usually called at the end of the program and we assume that it
413 // is *always* called at the end - so we free memory here to avoid false
414 // memory leak reports from wxWin memory tracking code
415 ClearTraceMasks();
416 }
417
418 void wxLog::RemoveTraceMask(const wxString& str)
419 {
420 int index = ms_aTraceMasks.Index(str);
421 if ( index != wxNOT_FOUND )
422 ms_aTraceMasks.Remove((size_t)index);
423 }
424
425 void wxLog::ClearTraceMasks()
426 {
427 ms_aTraceMasks.Clear();
428 }
429
430 void wxLog::TimeStamp(wxString *str)
431 {
432 if ( ms_timestamp )
433 {
434 wxChar buf[256];
435 time_t timeNow;
436 (void)time(&timeNow);
437 wxStrftime(buf, WXSIZEOF(buf), ms_timestamp, localtime(&timeNow));
438
439 str->Empty();
440 *str << buf << wxT(": ");
441 }
442 }
443
444 void wxLog::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
445 {
446 switch ( level ) {
447 case wxLOG_FatalError:
448 DoLogString(wxString(_("Fatal error: ")) + szString, t);
449 DoLogString(_("Program aborted."), t);
450 Flush();
451 abort();
452 break;
453
454 case wxLOG_Error:
455 DoLogString(wxString(_("Error: ")) + szString, t);
456 break;
457
458 case wxLOG_Warning:
459 DoLogString(wxString(_("Warning: ")) + szString, t);
460 break;
461
462 case wxLOG_Info:
463 if ( GetVerbose() )
464 case wxLOG_Message:
465 case wxLOG_Status:
466 default: // log unknown log levels too
467 DoLogString(szString, t);
468 break;
469
470 case wxLOG_Trace:
471 case wxLOG_Debug:
472 #ifdef __WXDEBUG__
473 {
474 wxString msg = level == wxLOG_Trace ? wxT("Trace: ")
475 : wxT("Debug: ");
476 msg << szString;
477 DoLogString(msg, t);
478 }
479 #endif // Debug
480 break;
481 }
482 }
483
484 void wxLog::DoLogString(const wxChar *WXUNUSED(szString), time_t WXUNUSED(t))
485 {
486 wxFAIL_MSG(wxT("DoLogString must be overriden if it's called."));
487 }
488
489 void wxLog::Flush()
490 {
491 // remember that we don't have any more messages to show
492 m_bHasMessages = FALSE;
493 }
494
495 // ----------------------------------------------------------------------------
496 // wxLogStderr class implementation
497 // ----------------------------------------------------------------------------
498
499 wxLogStderr::wxLogStderr(FILE *fp)
500 {
501 if ( fp == NULL )
502 m_fp = stderr;
503 else
504 m_fp = fp;
505 }
506
507 #if defined(__WXMAC__) && !defined(__DARWIN__) && (__MWERKS__ > 0x5300)
508
509 #if !TARGET_API_MAC_CARBON
510 // MetroNub stuff doesn't seem to work in CodeWarrior 5.3 Carbon builds...
511
512 #ifndef __MetroNubUtils__
513 #include "MetroNubUtils.h"
514 #endif
515
516 #ifdef __cplusplus
517 extern "C" {
518 #endif
519
520 #ifndef __GESTALT__
521 #include <Gestalt.h>
522 #endif
523
524 #ifndef true
525 #define true 1
526 #endif
527
528 #ifndef false
529 #define false 0
530 #endif
531
532 #if TARGET_API_MAC_CARBON
533
534 #include <CodeFragments.h>
535
536 EXTERN_API_C( long )
537 CallUniversalProc(UniversalProcPtr theProcPtr, ProcInfoType procInfo, ...);
538
539 ProcPtr gCallUniversalProc_Proc = NULL;
540
541 #endif
542
543 static MetroNubUserEntryBlock* gMetroNubEntry = NULL;
544
545 static long fRunOnce = false;
546
547 Boolean IsCompatibleVersion(short inVersion);
548
549 /* ---------------------------------------------------------------------------
550 IsCompatibleVersion
551 --------------------------------------------------------------------------- */
552
553 Boolean IsCompatibleVersion(short inVersion)
554 {
555 Boolean result = false;
556
557 if (fRunOnce)
558 {
559 MetroNubUserEntryBlock* block = (MetroNubUserEntryBlock *)result;
560
561 result = (inVersion <= block->apiHiVersion);
562 }
563
564 return result;
565 }
566
567 /* ---------------------------------------------------------------------------
568 IsMetroNubInstalled
569 --------------------------------------------------------------------------- */
570
571 Boolean IsMetroNubInstalled()
572 {
573 if (!fRunOnce)
574 {
575 long result, value;
576
577 fRunOnce = true;
578 gMetroNubEntry = NULL;
579
580 if (Gestalt(gestaltSystemVersion, &value) == noErr && value < 0x1000)
581 {
582 /* look for MetroNub's Gestalt selector */
583 if (Gestalt(kMetroNubUserSignature, &result) == noErr)
584 {
585
586 #if TARGET_API_MAC_CARBON
587 if (gCallUniversalProc_Proc == NULL)
588 {
589 CFragConnectionID connectionID;
590 Ptr mainAddress;
591 Str255 errorString;
592 ProcPtr symbolAddress;
593 OSErr err;
594 CFragSymbolClass symbolClass;
595
596 symbolAddress = NULL;
597 err = GetSharedLibrary("\pInterfaceLib", kPowerPCCFragArch, kFindCFrag,
598 &connectionID, &mainAddress, errorString);
599
600 if (err != noErr)
601 {
602 gCallUniversalProc_Proc = NULL;
603 goto end;
604 }
605
606 err = FindSymbol(connectionID, "\pCallUniversalProc",
607 (Ptr *) &gCallUniversalProc_Proc, &symbolClass);
608
609 if (err != noErr)
610 {
611 gCallUniversalProc_Proc = NULL;
612 goto end;
613 }
614 }
615 #endif
616
617 {
618 MetroNubUserEntryBlock* block = (MetroNubUserEntryBlock *)result;
619
620 /* make sure the version of the API is compatible */
621 if (block->apiLowVersion <= kMetroNubUserAPIVersion &&
622 kMetroNubUserAPIVersion <= block->apiHiVersion)
623 gMetroNubEntry = block; /* success! */
624 }
625
626 }
627 }
628 }
629
630 end:
631
632 #if TARGET_API_MAC_CARBON
633 return (gMetroNubEntry != NULL && gCallUniversalProc_Proc != NULL);
634 #else
635 return (gMetroNubEntry != NULL);
636 #endif
637 }
638
639 /* ---------------------------------------------------------------------------
640 IsMWDebuggerRunning [v1 API]
641 --------------------------------------------------------------------------- */
642
643 Boolean IsMWDebuggerRunning()
644 {
645 if (IsMetroNubInstalled())
646 return CallIsDebuggerRunningProc(gMetroNubEntry->isDebuggerRunning);
647 else
648 return false;
649 }
650
651 /* ---------------------------------------------------------------------------
652 AmIBeingMWDebugged [v1 API]
653 --------------------------------------------------------------------------- */
654
655 Boolean AmIBeingMWDebugged()
656 {
657 if (IsMetroNubInstalled())
658 return CallAmIBeingDebuggedProc(gMetroNubEntry->amIBeingDebugged);
659 else
660 return false;
661 }
662
663 /* ---------------------------------------------------------------------------
664 UserSetWatchPoint [v2 API]
665 --------------------------------------------------------------------------- */
666
667 OSErr UserSetWatchPoint (Ptr address, long length, WatchPointIDT* watchPointID)
668 {
669 if (IsMetroNubInstalled() && IsCompatibleVersion(kMetroNubUserAPIVersion))
670 return CallUserSetWatchPointProc(gMetroNubEntry->userSetWatchPoint,
671 address, length, watchPointID);
672 else
673 return errProcessIsNotClient;
674 }
675
676 /* ---------------------------------------------------------------------------
677 ClearWatchPoint [v2 API]
678 --------------------------------------------------------------------------- */
679
680 OSErr ClearWatchPoint (WatchPointIDT watchPointID)
681 {
682 if (IsMetroNubInstalled() && IsCompatibleVersion(kMetroNubUserAPIVersion))
683 return CallClearWatchPointProc(gMetroNubEntry->clearWatchPoint, watchPointID);
684 else
685 return errProcessIsNotClient;
686 }
687
688 #ifdef __cplusplus
689 }
690 #endif
691
692 #endif // !TARGET_API_MAC_CARBON
693
694 #endif // defined(__WXMAC__) && !defined(__DARWIN__) && (__MWERKS__ > 0x5300)
695
696 void wxLogStderr::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
697 {
698 wxString str;
699 TimeStamp(&str);
700 str << szString;
701
702 fputs(str.mb_str(), m_fp);
703 fputc(_T('\n'), m_fp);
704 fflush(m_fp);
705
706 // under Windows, programs usually don't have stderr at all, so show the
707 // messages also under debugger - unless it's a console program
708 #if defined(__WXMSW__) && wxUSE_GUI && !defined(__WXMICROWIN__)
709 str += wxT("\r\n") ;
710 OutputDebugString(str.c_str());
711 #endif // MSW
712 #if defined(__WXMAC__) && !defined(__DARWIN__) && wxUSE_GUI
713 Str255 pstr ;
714 strcpy( (char*) pstr , str.c_str() ) ;
715 strcat( (char*) pstr , ";g" ) ;
716 c2pstr( (char*) pstr ) ;
717
718 Boolean running = false ;
719
720 #if !TARGET_API_MAC_CARBON && (__MWERKS__ > 0x5300)
721
722 if ( IsMWDebuggerRunning() && AmIBeingMWDebugged() )
723 {
724 running = true ;
725 }
726
727 #endif
728
729 if (running)
730 {
731 #ifdef __powerc
732 DebugStr(pstr);
733 #else
734 SysBreakStr(pstr);
735 #endif
736 }
737 #endif // Mac
738 }
739
740 // ----------------------------------------------------------------------------
741 // wxLogStream implementation
742 // ----------------------------------------------------------------------------
743
744 #if wxUSE_STD_IOSTREAM
745 wxLogStream::wxLogStream(wxSTD ostream *ostr)
746 {
747 if ( ostr == NULL )
748 m_ostr = &wxSTD cerr;
749 else
750 m_ostr = ostr;
751 }
752
753 void wxLogStream::DoLogString(const wxChar *szString, time_t WXUNUSED(t))
754 {
755 wxString str;
756 TimeStamp(&str);
757 (*m_ostr) << str << wxConvertWX2MB(szString) << wxSTD endl;
758 }
759 #endif // wxUSE_STD_IOSTREAM
760
761 // ----------------------------------------------------------------------------
762 // wxLogChain
763 // ----------------------------------------------------------------------------
764
765 wxLogChain::wxLogChain(wxLog *logger)
766 {
767 m_bPassMessages = TRUE;
768
769 m_logNew = logger;
770 m_logOld = wxLog::SetActiveTarget(this);
771 }
772
773 wxLogChain::~wxLogChain()
774 {
775 delete m_logOld;
776
777 if ( m_logNew != this )
778 delete m_logNew;
779 }
780
781 void wxLogChain::SetLog(wxLog *logger)
782 {
783 if ( m_logNew != this )
784 delete m_logNew;
785
786 m_logNew = logger;
787 }
788
789 void wxLogChain::Flush()
790 {
791 if ( m_logOld )
792 m_logOld->Flush();
793
794 // be careful to avoid inifinite recursion
795 if ( m_logNew && m_logNew != this )
796 m_logNew->Flush();
797 }
798
799 void wxLogChain::DoLog(wxLogLevel level, const wxChar *szString, time_t t)
800 {
801 // let the previous logger show it
802 if ( m_logOld && IsPassingMessages() )
803 {
804 // bogus cast just to access protected DoLog
805 ((wxLogChain *)m_logOld)->DoLog(level, szString, t);
806 }
807
808 if ( m_logNew && m_logNew != this )
809 {
810 // as above...
811 ((wxLogChain *)m_logNew)->DoLog(level, szString, t);
812 }
813 }
814
815 // ----------------------------------------------------------------------------
816 // wxLogPassThrough
817 // ----------------------------------------------------------------------------
818
819 #ifdef __VISUALC__
820 // "'this' : used in base member initializer list" - so what?
821 #pragma warning(disable:4355)
822 #endif // VC++
823
824 wxLogPassThrough::wxLogPassThrough()
825 : wxLogChain(this)
826 {
827 }
828
829 #ifdef __VISUALC__
830 #pragma warning(default:4355)
831 #endif // VC++
832
833 // ============================================================================
834 // Global functions/variables
835 // ============================================================================
836
837 // ----------------------------------------------------------------------------
838 // static variables
839 // ----------------------------------------------------------------------------
840
841 wxLog *wxLog::ms_pLogger = (wxLog *)NULL;
842 bool wxLog::ms_doLog = TRUE;
843 bool wxLog::ms_bAutoCreate = TRUE;
844 bool wxLog::ms_bVerbose = FALSE;
845
846 size_t wxLog::ms_suspendCount = 0;
847
848 #if wxUSE_GUI
849 const wxChar *wxLog::ms_timestamp = wxT("%X"); // time only, no date
850 #else
851 const wxChar *wxLog::ms_timestamp = NULL; // save space
852 #endif
853
854 wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
855 wxArrayString wxLog::ms_aTraceMasks;
856
857 // ----------------------------------------------------------------------------
858 // stdout error logging helper
859 // ----------------------------------------------------------------------------
860
861 // helper function: wraps the message and justifies it under given position
862 // (looks more pretty on the terminal). Also adds newline at the end.
863 //
864 // TODO this is now disabled until I find a portable way of determining the
865 // terminal window size (ok, I found it but does anybody really cares?)
866 #ifdef LOG_PRETTY_WRAP
867 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
868 {
869 size_t nMax = 80; // FIXME
870 size_t nStart = strlen(pszPrefix);
871 fputs(pszPrefix, f);
872
873 size_t n;
874 while ( *psz != '\0' ) {
875 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
876 putc(*psz++, f);
877
878 // wrapped?
879 if ( *psz != '\0' ) {
880 /*putc('\n', f);*/
881 for ( n = 0; n < nStart; n++ )
882 putc(' ', f);
883
884 // as we wrapped, squeeze all white space
885 while ( isspace(*psz) )
886 psz++;
887 }
888 }
889
890 putc('\n', f);
891 }
892 #endif //LOG_PRETTY_WRAP
893
894 // ----------------------------------------------------------------------------
895 // error code/error message retrieval functions
896 // ----------------------------------------------------------------------------
897
898 // get error code from syste
899 unsigned long wxSysErrorCode()
900 {
901 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
902 #ifdef __WIN32__
903 return ::GetLastError();
904 #else //WIN16
905 // TODO what to do on Windows 3.1?
906 return 0;
907 #endif //WIN16/32
908 #else //Unix
909 return errno;
910 #endif //Win/Unix
911 }
912
913 // get error message from system
914 const wxChar *wxSysErrorMsg(unsigned long nErrCode)
915 {
916 if ( nErrCode == 0 )
917 nErrCode = wxSysErrorCode();
918
919 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
920 #ifdef __WIN32__
921 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
922
923 // get error message from system
924 LPVOID lpMsgBuf;
925 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
926 NULL, nErrCode,
927 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
928 (LPTSTR)&lpMsgBuf,
929 0, NULL);
930
931 // copy it to our buffer and free memory
932 if( lpMsgBuf != 0 ) {
933 wxStrncpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf) - 1);
934 s_szBuf[WXSIZEOF(s_szBuf) - 1] = wxT('\0');
935
936 LocalFree(lpMsgBuf);
937
938 // returned string is capitalized and ended with '\r\n' - bad
939 s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
940 size_t len = wxStrlen(s_szBuf);
941 if ( len > 0 ) {
942 // truncate string
943 if ( s_szBuf[len - 2] == wxT('\r') )
944 s_szBuf[len - 2] = wxT('\0');
945 }
946 }
947 else {
948 s_szBuf[0] = wxT('\0');
949 }
950
951 return s_szBuf;
952 #else //Win16
953 // TODO
954 return NULL;
955 #endif // Win16/32
956 #else // Unix
957 #if wxUSE_UNICODE
958 static wxChar s_szBuf[LOG_BUFFER_SIZE / 2];
959 wxConvCurrent->MB2WC(s_szBuf, strerror(nErrCode), WXSIZEOF(s_szBuf) -1);
960 return s_szBuf;
961 #else
962 return strerror((int)nErrCode);
963 #endif
964 #endif // Win/Unix
965 }
966
967 #endif //wxUSE_LOG
968
969 // vi:sts=4:sw=4:et