293fcd1dc8a10a75d34121fb79f260af8a8d3142
[wxWidgets.git] / src / common / log.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/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 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_LOG
28
29 // wxWidgets
30 #ifndef WX_PRECOMP
31 #include "wx/log.h"
32 #include "wx/app.h"
33 #include "wx/arrstr.h"
34 #include "wx/intl.h"
35 #include "wx/string.h"
36 #include "wx/utils.h"
37 #endif //WX_PRECOMP
38
39 #include "wx/apptrait.h"
40 #include "wx/datetime.h"
41 #include "wx/file.h"
42 #include "wx/msgout.h"
43 #include "wx/textfile.h"
44 #include "wx/thread.h"
45 #include "wx/private/threadinfo.h"
46 #include "wx/crt.h"
47 #include "wx/vector.h"
48
49 // other standard headers
50 #ifndef __WXWINCE__
51 #include <errno.h>
52 #endif
53
54 #include <stdlib.h>
55
56 #ifndef __WXPALMOS5__
57 #ifndef __WXWINCE__
58 #include <time.h>
59 #else
60 #include "wx/msw/wince/time.h"
61 #endif
62 #endif /* ! __WXPALMOS5__ */
63
64 #if defined(__WINDOWS__)
65 #include "wx/msw/private.h" // includes windows.h
66 #endif
67
68 #undef wxLOG_COMPONENT
69 const char *wxLOG_COMPONENT = "";
70
71 #if wxUSE_THREADS
72
73 wxTLS_TYPE(wxThreadSpecificInfo) wxThreadInfoVar;
74
75 namespace
76 {
77
78 // contains messages logged by the other threads and waiting to be shown until
79 // Flush() is called in the main one
80 typedef wxVector<wxLogRecord> wxLogRecords;
81 wxLogRecords gs_bufferedLogRecords;
82
83 // this macro allows to define an object which will be initialized before any
84 // other function in this file is called: this is necessary to allow log
85 // functions to be used during static initialization (this is not advisable
86 // anyhow but we should at least try to not crash) and to also ensure that they
87 // are initialized by the time static initialization is done, i.e. before any
88 // threads are created hopefully
89 //
90 // the net effect of all this is that you can use Get##name##CS() function to
91 // access the critical function without worrying about it being not initialized
92 //
93 // see also WX_DEFINE_GLOBAL_CONV2() in src/common/strconv.cpp
94 #define WX_DEFINE_LOG_CS(name) \
95 inline wxCriticalSection& Get##name##CS() \
96 { \
97 static wxCriticalSection s_cs##name; \
98 return s_cs##name; \
99 } \
100 \
101 wxCriticalSection *gs_##name##CSPtr = &Get##name##CS()
102
103 // this critical section is used for buffering the messages from threads other
104 // than main, i.e. it protects all accesses to gs_bufferedLogRecords above
105 WX_DEFINE_LOG_CS(BackgroundLog);
106
107 // this one is used for protecting ms_aTraceMasks from concurrent access
108 WX_DEFINE_LOG_CS(TraceMask);
109
110 // and this one is used for gs_componentLevels
111 WX_DEFINE_LOG_CS(Levels);
112
113 } // anonymous namespace
114
115 #endif // wxUSE_THREADS
116
117 // ----------------------------------------------------------------------------
118 // non member functions
119 // ----------------------------------------------------------------------------
120
121 // define this to enable wrapping of log messages
122 //#define LOG_PRETTY_WRAP
123
124 #ifdef LOG_PRETTY_WRAP
125 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz);
126 #endif
127
128 // ----------------------------------------------------------------------------
129 // module globals
130 // ----------------------------------------------------------------------------
131
132 namespace
133 {
134
135 // this struct is used to store information about the previous log message used
136 // by OnLog() to (optionally) avoid logging multiple copies of the same message
137 struct PreviousLogInfo
138 {
139 PreviousLogInfo()
140 {
141 numRepeated = 0;
142 }
143
144
145 // previous message itself
146 wxString msg;
147
148 // its level
149 wxLogLevel level;
150
151 // other information about it
152 wxLogRecordInfo info;
153
154 // the number of times it was already repeated
155 unsigned numRepeated;
156 };
157
158 PreviousLogInfo gs_prevLog;
159
160
161 // map containing all components for which log level was explicitly set
162 //
163 // NB: all accesses to it must be protected by GetLevelsCS() critical section
164 wxStringToNumHashMap gs_componentLevels;
165
166 } // anonymous namespace
167
168 // ============================================================================
169 // implementation
170 // ============================================================================
171
172 // ----------------------------------------------------------------------------
173 // helper global functions
174 // ----------------------------------------------------------------------------
175
176 void wxSafeShowMessage(const wxString& title, const wxString& text)
177 {
178 #ifdef __WINDOWS__
179 ::MessageBox(NULL, text.t_str(), title.t_str(), MB_OK | MB_ICONSTOP);
180 #else
181 wxFprintf(stderr, wxS("%s: %s\n"), title.c_str(), text.c_str());
182 fflush(stderr);
183 #endif
184 }
185
186 // ----------------------------------------------------------------------------
187 // wxLog class implementation
188 // ----------------------------------------------------------------------------
189
190 unsigned wxLog::LogLastRepeatIfNeeded()
191 {
192 const unsigned count = gs_prevLog.numRepeated;
193
194 if ( gs_prevLog.numRepeated )
195 {
196 wxString msg;
197 #if wxUSE_INTL
198 msg.Printf(wxPLURAL("The previous message repeated once.",
199 "The previous message repeated %lu times.",
200 gs_prevLog.numRepeated),
201 gs_prevLog.numRepeated);
202 #else
203 msg.Printf(wxS("The previous message was repeated %lu times."),
204 gs_prevLog.numRepeated);
205 #endif
206 gs_prevLog.numRepeated = 0;
207 gs_prevLog.msg.clear();
208 DoLogRecord(gs_prevLog.level, msg, gs_prevLog.info);
209 }
210
211 return count;
212 }
213
214 wxLog::~wxLog()
215 {
216 // Flush() must be called before destroying the object as otherwise some
217 // messages could be lost
218 if ( gs_prevLog.numRepeated )
219 {
220 wxMessageOutputDebug().Printf
221 (
222 wxS("Last repeated message (\"%s\", %lu times) wasn't output"),
223 gs_prevLog.msg,
224 gs_prevLog.numRepeated
225 );
226 }
227 }
228
229 // ----------------------------------------------------------------------------
230 // wxLog logging functions
231 // ----------------------------------------------------------------------------
232
233 /* static */
234 void
235 wxLog::OnLog(wxLogLevel level, const wxString& msg, time_t t)
236 {
237 wxLogRecordInfo info;
238 info.timestamp = t;
239 #if wxUSE_THREADS
240 info.threadId = wxThread::GetCurrentId();
241 #endif // wxUSE_THREADS
242
243 OnLog(level, msg, info);
244 }
245
246 /* static */
247 void
248 wxLog::OnLog(wxLogLevel level,
249 const wxString& msg,
250 const wxLogRecordInfo& info)
251 {
252 // fatal errors can't be suppressed nor handled by the custom log target
253 // and always terminate the program
254 if ( level == wxLOG_FatalError )
255 {
256 wxSafeShowMessage(wxS("Fatal Error"), msg);
257
258 #ifdef __WXWINCE__
259 ExitThread(3);
260 #else
261 abort();
262 #endif
263 }
264
265 wxLog *logger;
266
267 #if wxUSE_THREADS
268 if ( !wxThread::IsMain() )
269 {
270 logger = wxThreadInfo.logger;
271 if ( !logger )
272 {
273 if ( ms_pLogger )
274 {
275 // buffer the messages until they can be shown from the main
276 // thread
277 wxCriticalSectionLocker lock(GetBackgroundLogCS());
278
279 gs_bufferedLogRecords.push_back(wxLogRecord(level, msg, info));
280
281 // ensure that our Flush() will be called soon
282 wxWakeUpIdle();
283 }
284 //else: we don't have any logger at all, there is no need to log
285 // anything
286
287 return;
288 }
289 //else: we have a thread-specific logger, we can send messages to it
290 // directly
291 }
292 else
293 #endif // wxUSE_THREADS
294 {
295 logger = ms_pLogger;
296 if ( !logger )
297 return;
298 }
299
300 logger->CallDoLogNow(level, msg, info);
301 }
302
303 void
304 wxLog::CallDoLogNow(wxLogLevel level,
305 const wxString& msg,
306 const wxLogRecordInfo& info)
307 {
308 if ( GetRepetitionCounting() )
309 {
310 if ( msg == gs_prevLog.msg )
311 {
312 gs_prevLog.numRepeated++;
313
314 // nothing else to do, in particular, don't log the
315 // repeated message
316 return;
317 }
318
319 LogLastRepeatIfNeeded();
320
321 // reset repetition counter for a new message
322 gs_prevLog.msg = msg;
323 gs_prevLog.level = level;
324 gs_prevLog.info = info;
325 }
326
327 // handle extra data which may be passed to us by wxLogXXX()
328 wxString prefix, suffix;
329 wxUIntPtr num = 0;
330 if ( info.GetNumValue(wxLOG_KEY_SYS_ERROR_CODE, &num) )
331 {
332 long err = static_cast<long>(num);
333 if ( !err )
334 err = wxSysErrorCode();
335
336 suffix.Printf(_(" (error %ld: %s)"), err, wxSysErrorMsg(err));
337 }
338
339 #if wxUSE_LOG_TRACE
340 wxString str;
341 if ( level == wxLOG_Trace && info.GetStrValue(wxLOG_KEY_TRACE_MASK, &str) )
342 {
343 prefix = "(" + str + ") ";
344 }
345 #endif // wxUSE_LOG_TRACE
346
347 DoLogRecord(level, prefix + msg + suffix, info);
348 }
349
350 void wxLog::DoLogRecord(wxLogLevel level,
351 const wxString& msg,
352 const wxLogRecordInfo& info)
353 {
354 #if WXWIN_COMPATIBILITY_2_8
355 // call the old DoLog() to ensure that existing custom log classes still
356 // work
357 //
358 // as the user code could have defined it as either taking "const char *"
359 // (in ANSI build) or "const wxChar *" (in ANSI/Unicode), we have no choice
360 // but to call both of them
361 DoLog(level, (const char*)msg.mb_str(), info.timestamp);
362 DoLog(level, (const wchar_t*)msg.wc_str(), info.timestamp);
363 #endif // WXWIN_COMPATIBILITY_2_8
364
365
366 // TODO: it would be better to extract message formatting in a separate
367 // wxLogFormatter class but for now we hard code formatting here
368
369 wxString prefix;
370
371 // don't time stamp debug messages under MSW as debug viewers usually
372 // already have an option to do it
373 #ifdef __WXMSW__
374 if ( level != wxLOG_Debug && level != wxLOG_Trace )
375 #endif // __WXMSW__
376 TimeStamp(&prefix);
377
378 // TODO: use the other wxLogRecordInfo fields
379
380 switch ( level )
381 {
382 case wxLOG_Error:
383 prefix += _("Error: ");
384 break;
385
386 case wxLOG_Warning:
387 prefix += _("Warning: ");
388 break;
389
390 // don't prepend "debug/trace" prefix under MSW as it goes to the debug
391 // window anyhow and so can't be confused with something else
392 #ifndef __WXMSW__
393 case wxLOG_Debug:
394 // this prefix (as well as the one below) is intentionally not
395 // translated as nobody translates debug messages anyhow
396 prefix += "Debug: ";
397 break;
398
399 case wxLOG_Trace:
400 prefix += "Trace: ";
401 break;
402 #endif // !__WXMSW__
403 }
404
405 DoLogTextAtLevel(level, prefix + msg);
406 }
407
408 void wxLog::DoLogTextAtLevel(wxLogLevel level, const wxString& msg)
409 {
410 // we know about debug messages (because using wxMessageOutputDebug is the
411 // right thing to do in 99% of all cases and also for compatibility) but
412 // anything else needs to be handled in the derived class
413 if ( level == wxLOG_Debug || level == wxLOG_Trace )
414 {
415 wxMessageOutputDebug().Output(msg + wxS('\n'));
416 }
417 else
418 {
419 DoLogText(msg);
420 }
421 }
422
423 void wxLog::DoLogText(const wxString& WXUNUSED(msg))
424 {
425 // in 2.8-compatible build the derived class might override DoLog() or
426 // DoLogString() instead so we can't have this assert there
427 #if !WXWIN_COMPATIBILITY_2_8
428 wxFAIL_MSG( "must be overridden if it is called" );
429 #endif // WXWIN_COMPATIBILITY_2_8
430 }
431
432 #if WXWIN_COMPATIBILITY_2_8
433
434 void wxLog::DoLog(wxLogLevel WXUNUSED(level), const char *szString, time_t t)
435 {
436 DoLogString(szString, t);
437 }
438
439 void wxLog::DoLog(wxLogLevel WXUNUSED(level), const wchar_t *wzString, time_t t)
440 {
441 DoLogString(wzString, t);
442 }
443
444 #endif // WXWIN_COMPATIBILITY_2_8
445
446 // ----------------------------------------------------------------------------
447 // wxLog active target management
448 // ----------------------------------------------------------------------------
449
450 wxLog *wxLog::GetActiveTarget()
451 {
452 #if wxUSE_THREADS
453 if ( !wxThread::IsMain() )
454 {
455 // check if we have a thread-specific log target
456 wxLog * const logger = wxThreadInfo.logger;
457
458 // the code below should be only executed for the main thread as
459 // CreateLogTarget() is not meant for auto-creating log targets for
460 // worker threads so skip it in any case
461 return logger ? logger : ms_pLogger;
462 }
463 #endif // wxUSE_THREADS
464
465 if ( ms_bAutoCreate && ms_pLogger == NULL ) {
466 // prevent infinite recursion if someone calls wxLogXXX() from
467 // wxApp::CreateLogTarget()
468 static bool s_bInGetActiveTarget = false;
469 if ( !s_bInGetActiveTarget ) {
470 s_bInGetActiveTarget = true;
471
472 // ask the application to create a log target for us
473 if ( wxTheApp != NULL )
474 ms_pLogger = wxTheApp->GetTraits()->CreateLogTarget();
475 else
476 ms_pLogger = new wxLogStderr;
477
478 s_bInGetActiveTarget = false;
479
480 // do nothing if it fails - what can we do?
481 }
482 }
483
484 return ms_pLogger;
485 }
486
487 wxLog *wxLog::SetActiveTarget(wxLog *pLogger)
488 {
489 if ( ms_pLogger != NULL ) {
490 // flush the old messages before changing because otherwise they might
491 // get lost later if this target is not restored
492 ms_pLogger->Flush();
493 }
494
495 wxLog *pOldLogger = ms_pLogger;
496 ms_pLogger = pLogger;
497
498 return pOldLogger;
499 }
500
501 #if wxUSE_THREADS
502 /* static */
503 wxLog *wxLog::SetThreadActiveTarget(wxLog *logger)
504 {
505 wxASSERT_MSG( !wxThread::IsMain(), "use SetActiveTarget() for main thread" );
506
507 wxLog * const oldLogger = wxThreadInfo.logger;
508 if ( oldLogger )
509 oldLogger->Flush();
510
511 wxThreadInfo.logger = logger;
512
513 return oldLogger;
514 }
515 #endif // wxUSE_THREADS
516
517 void wxLog::DontCreateOnDemand()
518 {
519 ms_bAutoCreate = false;
520
521 // this is usually called at the end of the program and we assume that it
522 // is *always* called at the end - so we free memory here to avoid false
523 // memory leak reports from wxWin memory tracking code
524 ClearTraceMasks();
525 }
526
527 void wxLog::DoCreateOnDemand()
528 {
529 ms_bAutoCreate = true;
530 }
531
532 // ----------------------------------------------------------------------------
533 // wxLog components levels
534 // ----------------------------------------------------------------------------
535
536 /* static */
537 void wxLog::SetComponentLevel(const wxString& component, wxLogLevel level)
538 {
539 if ( component.empty() )
540 {
541 SetLogLevel(level);
542 }
543 else
544 {
545 wxCRIT_SECT_LOCKER(lock, GetLevelsCS());
546
547 gs_componentLevels[component] = level;
548 }
549 }
550
551 /* static */
552 wxLogLevel wxLog::GetComponentLevel(wxString component)
553 {
554 wxCRIT_SECT_LOCKER(lock, GetLevelsCS());
555
556 while ( !component.empty() )
557 {
558 wxStringToNumHashMap::const_iterator
559 it = gs_componentLevels.find(component);
560 if ( it != gs_componentLevels.end() )
561 return static_cast<wxLogLevel>(it->second);
562
563 component = component.BeforeLast('/');
564 }
565
566 return GetLogLevel();
567 }
568
569 // ----------------------------------------------------------------------------
570 // wxLog trace masks
571 // ----------------------------------------------------------------------------
572
573 void wxLog::AddTraceMask(const wxString& str)
574 {
575 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
576
577 ms_aTraceMasks.push_back(str);
578 }
579
580 void wxLog::RemoveTraceMask(const wxString& str)
581 {
582 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
583
584 int index = ms_aTraceMasks.Index(str);
585 if ( index != wxNOT_FOUND )
586 ms_aTraceMasks.RemoveAt((size_t)index);
587 }
588
589 void wxLog::ClearTraceMasks()
590 {
591 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
592
593 ms_aTraceMasks.Clear();
594 }
595
596 /*static*/ bool wxLog::IsAllowedTraceMask(const wxString& mask)
597 {
598 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
599
600 for ( wxArrayString::iterator it = ms_aTraceMasks.begin(),
601 en = ms_aTraceMasks.end();
602 it != en; ++it )
603 {
604 if ( *it == mask)
605 return true;
606 }
607
608 return false;
609 }
610
611 // ----------------------------------------------------------------------------
612 // wxLog miscellaneous other methods
613 // ----------------------------------------------------------------------------
614
615 void wxLog::TimeStamp(wxString *str)
616 {
617 #if wxUSE_DATETIME
618 if ( !ms_timestamp.empty() )
619 {
620 wxChar buf[256];
621 time_t timeNow;
622 (void)time(&timeNow);
623
624 struct tm tm;
625 wxStrftime(buf, WXSIZEOF(buf),
626 ms_timestamp, wxLocaltime_r(&timeNow, &tm));
627
628 str->Empty();
629 *str << buf << wxS(": ");
630 }
631 #endif // wxUSE_DATETIME
632 }
633
634 #if wxUSE_THREADS
635
636 void wxLog::FlushThreadMessages()
637 {
638 // check if we have queued messages from other threads
639 wxLogRecords bufferedLogRecords;
640
641 {
642 wxCriticalSectionLocker lock(GetBackgroundLogCS());
643 bufferedLogRecords.swap(gs_bufferedLogRecords);
644
645 // release the lock now to not keep it while we are logging the
646 // messages below, allowing background threads to run
647 }
648
649 if ( !bufferedLogRecords.empty() )
650 {
651 for ( wxLogRecords::const_iterator it = bufferedLogRecords.begin();
652 it != bufferedLogRecords.end();
653 ++it )
654 {
655 CallDoLogNow(it->level, it->msg, it->info);
656 }
657 }
658 }
659
660 #endif // wxUSE_THREADS
661
662 void wxLog::Flush()
663 {
664 LogLastRepeatIfNeeded();
665 }
666
667 /* static */
668 void wxLog::FlushActive()
669 {
670 if ( ms_suspendCount )
671 return;
672
673 wxLog * const log = GetActiveTarget();
674 if ( log )
675 {
676 #if wxUSE_THREADS
677 if ( wxThread::IsMain() )
678 log->FlushThreadMessages();
679 #endif // wxUSE_THREADS
680
681 log->Flush();
682 }
683 }
684
685 // ----------------------------------------------------------------------------
686 // wxLogBuffer implementation
687 // ----------------------------------------------------------------------------
688
689 void wxLogBuffer::Flush()
690 {
691 wxLog::Flush();
692
693 if ( !m_str.empty() )
694 {
695 wxMessageOutputBest out;
696 out.Printf(wxS("%s"), m_str.c_str());
697 m_str.clear();
698 }
699 }
700
701 void wxLogBuffer::DoLogTextAtLevel(wxLogLevel level, const wxString& msg)
702 {
703 // don't put debug messages in the buffer, we don't want to show
704 // them to the user in a msg box, log them immediately
705 switch ( level )
706 {
707 case wxLOG_Debug:
708 case wxLOG_Trace:
709 wxLog::DoLogTextAtLevel(level, msg);
710 break;
711
712 default:
713 m_str << msg << wxS("\n");
714 }
715 }
716
717 // ----------------------------------------------------------------------------
718 // wxLogStderr class implementation
719 // ----------------------------------------------------------------------------
720
721 wxLogStderr::wxLogStderr(FILE *fp)
722 {
723 if ( fp == NULL )
724 m_fp = stderr;
725 else
726 m_fp = fp;
727 }
728
729 void wxLogStderr::DoLogText(const wxString& msg)
730 {
731 wxFputs(msg + '\n', m_fp);
732 fflush(m_fp);
733
734 // under GUI systems such as Windows or Mac, programs usually don't have
735 // stderr at all, so show the messages also somewhere else, typically in
736 // the debugger window so that they go at least somewhere instead of being
737 // simply lost
738 if ( m_fp == stderr )
739 {
740 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
741 if ( traits && !traits->HasStderr() )
742 {
743 wxMessageOutputDebug().Output(msg + wxS('\n'));
744 }
745 }
746 }
747
748 // ----------------------------------------------------------------------------
749 // wxLogStream implementation
750 // ----------------------------------------------------------------------------
751
752 #if wxUSE_STD_IOSTREAM
753 #include "wx/ioswrap.h"
754 wxLogStream::wxLogStream(wxSTD ostream *ostr)
755 {
756 if ( ostr == NULL )
757 m_ostr = &wxSTD cerr;
758 else
759 m_ostr = ostr;
760 }
761
762 void wxLogStream::DoLogText(const wxString& msg)
763 {
764 (*m_ostr) << msg << 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::DoLogRecord(wxLogLevel level,
807 const wxString& msg,
808 const wxLogRecordInfo& info)
809 {
810 // let the previous logger show it
811 if ( m_logOld && IsPassingMessages() )
812 m_logOld->LogRecord(level, msg, info);
813
814 // and also send it to the new one
815 if ( m_logNew && m_logNew != this )
816 m_logNew->LogRecord(level, msg, info);
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 // ----------------------------------------------------------------------------
825 // wxLogInterposer
826 // ----------------------------------------------------------------------------
827
828 wxLogInterposer::wxLogInterposer()
829 : wxLogChain(this)
830 {
831 }
832
833 // ----------------------------------------------------------------------------
834 // wxLogInterposerTemp
835 // ----------------------------------------------------------------------------
836
837 wxLogInterposerTemp::wxLogInterposerTemp()
838 : wxLogChain(this)
839 {
840 DetachOldLog();
841 }
842
843 #ifdef __VISUALC__
844 #pragma warning(default:4355)
845 #endif // VC++
846
847 // ============================================================================
848 // Global functions/variables
849 // ============================================================================
850
851 // ----------------------------------------------------------------------------
852 // static variables
853 // ----------------------------------------------------------------------------
854
855 bool wxLog::ms_bRepetCounting = false;
856
857 wxLog *wxLog::ms_pLogger = NULL;
858 bool wxLog::ms_doLog = true;
859 bool wxLog::ms_bAutoCreate = true;
860 bool wxLog::ms_bVerbose = false;
861
862 wxLogLevel wxLog::ms_logLevel = wxLOG_Max; // log everything by default
863
864 size_t wxLog::ms_suspendCount = 0;
865
866 wxString wxLog::ms_timestamp(wxS("%X")); // time only, no date
867
868 #if WXWIN_COMPATIBILITY_2_8
869 wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
870 #endif // wxDEBUG_LEVEL
871
872 wxArrayString wxLog::ms_aTraceMasks;
873
874 // ----------------------------------------------------------------------------
875 // stdout error logging helper
876 // ----------------------------------------------------------------------------
877
878 // helper function: wraps the message and justifies it under given position
879 // (looks more pretty on the terminal). Also adds newline at the end.
880 //
881 // TODO this is now disabled until I find a portable way of determining the
882 // terminal window size (ok, I found it but does anybody really cares?)
883 #ifdef LOG_PRETTY_WRAP
884 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
885 {
886 size_t nMax = 80; // FIXME
887 size_t nStart = strlen(pszPrefix);
888 fputs(pszPrefix, f);
889
890 size_t n;
891 while ( *psz != '\0' ) {
892 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
893 putc(*psz++, f);
894
895 // wrapped?
896 if ( *psz != '\0' ) {
897 /*putc('\n', f);*/
898 for ( n = 0; n < nStart; n++ )
899 putc(' ', f);
900
901 // as we wrapped, squeeze all white space
902 while ( isspace(*psz) )
903 psz++;
904 }
905 }
906
907 putc('\n', f);
908 }
909 #endif //LOG_PRETTY_WRAP
910
911 // ----------------------------------------------------------------------------
912 // error code/error message retrieval functions
913 // ----------------------------------------------------------------------------
914
915 // get error code from syste
916 unsigned long wxSysErrorCode()
917 {
918 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
919 return ::GetLastError();
920 #else //Unix
921 return errno;
922 #endif //Win/Unix
923 }
924
925 // get error message from system
926 const wxChar *wxSysErrorMsg(unsigned long nErrCode)
927 {
928 if ( nErrCode == 0 )
929 nErrCode = wxSysErrorCode();
930
931 #if defined(__WXMSW__) && !defined(__WXMICROWIN__)
932 static wxChar s_szBuf[1024];
933
934 // get error message from system
935 LPVOID lpMsgBuf;
936 if ( ::FormatMessage
937 (
938 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
939 NULL,
940 nErrCode,
941 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
942 (LPTSTR)&lpMsgBuf,
943 0,
944 NULL
945 ) == 0 )
946 {
947 // if this happens, something is seriously wrong, so don't use _() here
948 // for safety
949 wxSprintf(s_szBuf, wxS("unknown error %lx"), nErrCode);
950 return s_szBuf;
951 }
952
953
954 // copy it to our buffer and free memory
955 // Crashes on SmartPhone (FIXME)
956 #if !defined(__SMARTPHONE__) /* of WinCE */
957 if( lpMsgBuf != 0 )
958 {
959 wxStrlcpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf));
960
961 LocalFree(lpMsgBuf);
962
963 // returned string is capitalized and ended with '\r\n' - bad
964 s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
965 size_t len = wxStrlen(s_szBuf);
966 if ( len > 0 ) {
967 // truncate string
968 if ( s_szBuf[len - 2] == wxS('\r') )
969 s_szBuf[len - 2] = wxS('\0');
970 }
971 }
972 else
973 #endif // !__SMARTPHONE__
974 {
975 s_szBuf[0] = wxS('\0');
976 }
977
978 return s_szBuf;
979 #else // !__WXMSW__
980 #if wxUSE_UNICODE
981 static wchar_t s_wzBuf[1024];
982 wxConvCurrent->MB2WC(s_wzBuf, strerror((int)nErrCode),
983 WXSIZEOF(s_wzBuf) - 1);
984 return s_wzBuf;
985 #else
986 return strerror((int)nErrCode);
987 #endif
988 #endif // __WXMSW__/!__WXMSW__
989 }
990
991 #endif // wxUSE_LOG