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