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