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