]> git.saurik.com Git - wxWidgets.git/blame - src/common/log.cpp
Dramatically optimise inserting many items in wxGenericListCtrl.
[wxWidgets.git] / src / common / log.cpp
CommitLineData
c801d85f 1/////////////////////////////////////////////////////////////////////////////
e4db172a 2// Name: src/common/log.cpp
c801d85f
KB
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>
65571936 9// Licence: wxWindows licence
c801d85f
KB
10/////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
dd85fc6b 19
c801d85f
KB
20// For compilers that support precompilation, includes "wx.h".
21#include "wx/wxprec.h"
22
23#ifdef __BORLANDC__
e2478fde 24 #pragma hdrstop
c801d85f
KB
25#endif
26
e2478fde
VZ
27#if wxUSE_LOG
28
77ffb593 29// wxWidgets
c801d85f 30#ifndef WX_PRECOMP
e4db172a 31 #include "wx/log.h"
e90c1d2a 32 #include "wx/app.h"
df5168c4 33 #include "wx/arrstr.h"
e2478fde
VZ
34 #include "wx/intl.h"
35 #include "wx/string.h"
de6185e2 36 #include "wx/utils.h"
9ef3052c 37#endif //WX_PRECOMP
c801d85f 38
e2478fde 39#include "wx/apptrait.h"
7b2d1c74 40#include "wx/datetime.h"
e2478fde 41#include "wx/file.h"
e2478fde
VZ
42#include "wx/msgout.h"
43#include "wx/textfile.h"
44#include "wx/thread.h"
acad886c 45#include "wx/private/threadinfo.h"
3a3dde0d 46#include "wx/crt.h"
232addd1 47#include "wx/vector.h"
f94dfb38 48
c801d85f 49// other standard headers
1c193821 50#ifndef __WXWINCE__
e2478fde 51#include <errno.h>
1c193821
JS
52#endif
53
e2478fde 54#include <stdlib.h>
1c193821 55
9b4da627 56#ifndef __WXPALMOS5__
1c193821 57#ifndef __WXWINCE__
e2478fde 58#include <time.h>
1c193821
JS
59#else
60#include "wx/msw/wince/time.h"
61#endif
9b4da627 62#endif /* ! __WXPALMOS5__ */
31907d03 63
9cce3be7
VS
64#if defined(__WINDOWS__)
65 #include "wx/msw/private.h" // includes windows.h
66#endif
67
c602c59b
VZ
68#undef wxLOG_COMPONENT
69const char *wxLOG_COMPONENT = "";
70
d5e7d2ec
VZ
71// this macro allows to define an object which will be initialized before any
72// other function in this file is called: this is necessary to allow log
73// functions to be used during static initialization (this is not advisable
74// anyhow but we should at least try to not crash) and to also ensure that they
75// are initialized by the time static initialization is done, i.e. before any
76// threads are created hopefully
77//
bc1e0d4d
VZ
78// the net effect of all this is that you can use Get##name() function to
79// access the object without worrying about it being not initialized
d5e7d2ec
VZ
80//
81// see also WX_DEFINE_GLOBAL_CONV2() in src/common/strconv.cpp
bc1e0d4d
VZ
82#define WX_DEFINE_GLOBAL_VAR(type, name) \
83 inline type& Get##name() \
d5e7d2ec 84 { \
bc1e0d4d
VZ
85 static type s_##name; \
86 return s_##name; \
d5e7d2ec
VZ
87 } \
88 \
bc1e0d4d
VZ
89 type *gs_##name##Ptr = &Get##name()
90
9d7cb671
VZ
91#if wxUSE_THREADS
92
93wxTLS_TYPE(wxThreadSpecificInfo) wxThreadInfoVar;
94
bc1e0d4d
VZ
95namespace
96{
97
98// contains messages logged by the other threads and waiting to be shown until
99// Flush() is called in the main one
100typedef wxVector<wxLogRecord> wxLogRecords;
101wxLogRecords gs_bufferedLogRecords;
102
103#define WX_DEFINE_LOG_CS(name) WX_DEFINE_GLOBAL_VAR(wxCriticalSection, name##CS)
766aecab 104
232addd1
VZ
105// this critical section is used for buffering the messages from threads other
106// than main, i.e. it protects all accesses to gs_bufferedLogRecords above
d5e7d2ec 107WX_DEFINE_LOG_CS(BackgroundLog);
232addd1 108
55e5154d 109// this one is used for protecting TraceMasks() from concurrent access
d5e7d2ec 110WX_DEFINE_LOG_CS(TraceMask);
c602c59b 111
03647350 112// and this one is used for GetComponentLevels()
d5e7d2ec 113WX_DEFINE_LOG_CS(Levels);
c602c59b 114
232addd1
VZ
115} // anonymous namespace
116
766aecab
VZ
117#endif // wxUSE_THREADS
118
c801d85f
KB
119// ----------------------------------------------------------------------------
120// non member functions
121// ----------------------------------------------------------------------------
122
123// define this to enable wrapping of log messages
124//#define LOG_PRETTY_WRAP
125
9ef3052c 126#ifdef LOG_PRETTY_WRAP
c801d85f
KB
127 static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz);
128#endif
129
bc73d5ae
VZ
130// ----------------------------------------------------------------------------
131// module globals
132// ----------------------------------------------------------------------------
133
134namespace
135{
136
137// this struct is used to store information about the previous log message used
138// by OnLog() to (optionally) avoid logging multiple copies of the same message
139struct PreviousLogInfo
140{
141 PreviousLogInfo()
142 {
143 numRepeated = 0;
144 }
145
146
147 // previous message itself
148 wxString msg;
149
150 // its level
151 wxLogLevel level;
152
153 // other information about it
154 wxLogRecordInfo info;
155
156 // the number of times it was already repeated
157 unsigned numRepeated;
158};
159
160PreviousLogInfo gs_prevLog;
161
c602c59b
VZ
162
163// map containing all components for which log level was explicitly set
164//
165// NB: all accesses to it must be protected by GetLevelsCS() critical section
bc1e0d4d 166WX_DEFINE_GLOBAL_VAR(wxStringToNumHashMap, ComponentLevels);
c602c59b 167
55b24eb8
VZ
168// ----------------------------------------------------------------------------
169// wxLogOutputBest: wxLog wrapper around wxMessageOutputBest
170// ----------------------------------------------------------------------------
171
172class wxLogOutputBest : public wxLog
173{
174public:
175 wxLogOutputBest() { }
176
177protected:
178 virtual void DoLogText(const wxString& msg)
179 {
180 wxMessageOutputBest().Output(msg);
181 }
182
183private:
184 wxDECLARE_NO_COPY_CLASS(wxLogOutputBest);
185};
186
bc73d5ae
VZ
187} // anonymous namespace
188
c801d85f
KB
189// ============================================================================
190// implementation
191// ============================================================================
192
b568d04f 193// ----------------------------------------------------------------------------
af588446 194// helper global functions
b568d04f
VZ
195// ----------------------------------------------------------------------------
196
c11d62a6
VZ
197void wxSafeShowMessage(const wxString& title, const wxString& text)
198{
199#ifdef __WINDOWS__
dc874fb4 200 ::MessageBox(NULL, text.t_str(), title.t_str(), MB_OK | MB_ICONSTOP);
c11d62a6 201#else
a0516656 202 wxFprintf(stderr, wxS("%s: %s\n"), title.c_str(), text.c_str());
65f06384 203 fflush(stderr);
c11d62a6
VZ
204#endif
205}
206
4ffdb640
VZ
207// ----------------------------------------------------------------------------
208// wxLogFormatter class implementation
209// ----------------------------------------------------------------------------
210
211wxString
212wxLogFormatter::Format(wxLogLevel level,
213 const wxString& msg,
214 const wxLogRecordInfo& info) const
215{
216 wxString prefix = FormatTime(info.timestamp);
217
218 switch ( level )
219 {
220 case wxLOG_Error:
221 prefix += _("Error: ");
222 break;
223
224 case wxLOG_Warning:
225 prefix += _("Warning: ");
226 break;
227
228 // don't prepend "debug/trace" prefix under MSW as it goes to the debug
229 // window anyhow and so can't be confused with something else
230#ifndef __WXMSW__
231 case wxLOG_Debug:
232 // this prefix (as well as the one below) is intentionally not
233 // translated as nobody translates debug messages anyhow
234 prefix += "Debug: ";
235 break;
236
237 case wxLOG_Trace:
238 prefix += "Trace: ";
239 break;
240#endif // !__WXMSW__
241 }
242
243 return prefix + msg;
244}
245
246wxString
247wxLogFormatter::FormatTime(time_t t) const
248{
249 wxString str;
250
251 // don't time stamp debug messages under MSW as debug viewers usually
252 // already have an option to do it
253#ifdef __WXMSW__
254 if ( level != wxLOG_Debug && level != wxLOG_Trace )
255#endif // __WXMSW__
256 wxLog::TimeStamp(&str, t);
257
258 return str;
259}
260
261
c801d85f
KB
262// ----------------------------------------------------------------------------
263// wxLog class implementation
264// ----------------------------------------------------------------------------
265
dbaa16de 266unsigned wxLog::LogLastRepeatIfNeeded()
dbaa16de 267{
bc73d5ae 268 const unsigned count = gs_prevLog.numRepeated;
0250efd6 269
bc73d5ae 270 if ( gs_prevLog.numRepeated )
f9837791
VZ
271 {
272 wxString msg;
459b97df 273#if wxUSE_INTL
23717034
VZ
274 if ( gs_prevLog.numRepeated == 1 )
275 {
276 // We use a separate message for this case as "repeated 1 time"
277 // looks somewhat strange.
278 msg = _("The previous message repeated once.");
279 }
280 else
281 {
282 // Notice that we still use wxPLURAL() to ensure that multiple
283 // numbers of times are correctly formatted, even though we never
284 // actually use the singular string.
285 msg.Printf(wxPLURAL("The previous message repeated %lu time.",
286 "The previous message repeated %lu times.",
287 gs_prevLog.numRepeated),
288 gs_prevLog.numRepeated);
289 }
459b97df 290#else
23717034 291 msg.Printf(wxS("The previous message was repeated %lu time(s)."),
bc73d5ae 292 gs_prevLog.numRepeated);
459b97df 293#endif
bc73d5ae
VZ
294 gs_prevLog.numRepeated = 0;
295 gs_prevLog.msg.clear();
296 DoLogRecord(gs_prevLog.level, msg, gs_prevLog.info);
f9837791 297 }
0250efd6
VZ
298
299 return count;
f9837791
VZ
300}
301
302wxLog::~wxLog()
303{
6f6b48f1
VZ
304 // Flush() must be called before destroying the object as otherwise some
305 // messages could be lost
bc73d5ae 306 if ( gs_prevLog.numRepeated )
6f6b48f1
VZ
307 {
308 wxMessageOutputDebug().Printf
309 (
c977643b
VZ
310#if wxUSE_INTL
311 wxPLURAL
312 (
313 "Last repeated message (\"%s\", %lu time) wasn't output",
314 "Last repeated message (\"%s\", %lu times) wasn't output",
315 gs_prevLog.numRepeated
316 ),
317#else
318 wxS("Last repeated message (\"%s\", %lu time(s)) wasn't output"),
319#endif
bc73d5ae
VZ
320 gs_prevLog.msg,
321 gs_prevLog.numRepeated
6f6b48f1
VZ
322 );
323 }
4ffdb640
VZ
324
325 delete m_formatter;
f9837791
VZ
326}
327
bc73d5ae
VZ
328// ----------------------------------------------------------------------------
329// wxLog logging functions
330// ----------------------------------------------------------------------------
331
332/* static */
333void
334wxLog::OnLog(wxLogLevel level, const wxString& msg, time_t t)
335{
336 wxLogRecordInfo info;
337 info.timestamp = t;
338#if wxUSE_THREADS
339 info.threadId = wxThread::GetCurrentId();
340#endif // wxUSE_THREADS
341
342 OnLog(level, msg, info);
343}
344
f9837791 345/* static */
bc73d5ae
VZ
346void
347wxLog::OnLog(wxLogLevel level,
348 const wxString& msg,
349 const wxLogRecordInfo& info)
f9837791 350{
af588446
VZ
351 // fatal errors can't be suppressed nor handled by the custom log target
352 // and always terminate the program
353 if ( level == wxLOG_FatalError )
f9837791 354 {
af588446 355 wxSafeShowMessage(wxS("Fatal Error"), msg);
a2d38265 356
af588446
VZ
357#ifdef __WXWINCE__
358 ExitThread(3);
359#else
360 abort();
361#endif
362 }
2064113c 363
acad886c 364 wxLog *logger;
2064113c 365
232addd1
VZ
366#if wxUSE_THREADS
367 if ( !wxThread::IsMain() )
368 {
acad886c
VZ
369 logger = wxThreadInfo.logger;
370 if ( !logger )
371 {
372 if ( ms_pLogger )
373 {
374 // buffer the messages until they can be shown from the main
375 // thread
376 wxCriticalSectionLocker lock(GetBackgroundLogCS());
232addd1 377
acad886c 378 gs_bufferedLogRecords.push_back(wxLogRecord(level, msg, info));
232addd1 379
acad886c
VZ
380 // ensure that our Flush() will be called soon
381 wxWakeUpIdle();
382 }
383 //else: we don't have any logger at all, there is no need to log
384 // anything
232addd1 385
acad886c
VZ
386 return;
387 }
388 //else: we have a thread-specific logger, we can send messages to it
389 // directly
232addd1 390 }
acad886c 391 else
232addd1 392#endif // wxUSE_THREADS
acad886c 393 {
5d7526b0 394 logger = GetMainThreadActiveTarget();
acad886c
VZ
395 if ( !logger )
396 return;
397 }
232addd1 398
acad886c 399 logger->CallDoLogNow(level, msg, info);
232addd1
VZ
400}
401
402void
acad886c
VZ
403wxLog::CallDoLogNow(wxLogLevel level,
404 const wxString& msg,
405 const wxLogRecordInfo& info)
232addd1 406{
af588446
VZ
407 if ( GetRepetitionCounting() )
408 {
af588446
VZ
409 if ( msg == gs_prevLog.msg )
410 {
411 gs_prevLog.numRepeated++;
2064113c 412
af588446
VZ
413 // nothing else to do, in particular, don't log the
414 // repeated message
415 return;
f9837791 416 }
af588446 417
16b1f6fc 418 LogLastRepeatIfNeeded();
af588446
VZ
419
420 // reset repetition counter for a new message
421 gs_prevLog.msg = msg;
422 gs_prevLog.level = level;
423 gs_prevLog.info = info;
f9837791 424 }
af588446
VZ
425
426 // handle extra data which may be passed to us by wxLogXXX()
427 wxString prefix, suffix;
0758c46e 428 wxUIntPtr num = 0;
af588446
VZ
429 if ( info.GetNumValue(wxLOG_KEY_SYS_ERROR_CODE, &num) )
430 {
b804f992 431 const long err = static_cast<long>(num);
af588446
VZ
432
433 suffix.Printf(_(" (error %ld: %s)"), err, wxSysErrorMsg(err));
434 }
435
436#if wxUSE_LOG_TRACE
437 wxString str;
438 if ( level == wxLOG_Trace && info.GetStrValue(wxLOG_KEY_TRACE_MASK, &str) )
439 {
440 prefix = "(" + str + ") ";
441 }
442#endif // wxUSE_LOG_TRACE
443
232addd1 444 DoLogRecord(level, prefix + msg + suffix, info);
f9837791
VZ
445}
446
bc73d5ae
VZ
447void wxLog::DoLogRecord(wxLogLevel level,
448 const wxString& msg,
449 const wxLogRecordInfo& info)
04662def 450{
bc73d5ae
VZ
451#if WXWIN_COMPATIBILITY_2_8
452 // call the old DoLog() to ensure that existing custom log classes still
453 // work
454 //
455 // as the user code could have defined it as either taking "const char *"
456 // (in ANSI build) or "const wxChar *" (in ANSI/Unicode), we have no choice
457 // but to call both of them
458 DoLog(level, (const char*)msg.mb_str(), info.timestamp);
459 DoLog(level, (const wchar_t*)msg.wc_str(), info.timestamp);
36a6cfd2
VZ
460#else // !WXWIN_COMPATIBILITY_2_8
461 wxUnusedVar(info);
462#endif // WXWIN_COMPATIBILITY_2_8/!WXWIN_COMPATIBILITY_2_8
bc73d5ae 463
4ffdb640
VZ
464 // Use wxLogFormatter to format the message
465 DoLogTextAtLevel(level, m_formatter->Format (level, msg, info));
04662def
RL
466}
467
bc73d5ae
VZ
468void wxLog::DoLogTextAtLevel(wxLogLevel level, const wxString& msg)
469{
470 // we know about debug messages (because using wxMessageOutputDebug is the
471 // right thing to do in 99% of all cases and also for compatibility) but
472 // anything else needs to be handled in the derived class
473 if ( level == wxLOG_Debug || level == wxLOG_Trace )
474 {
475 wxMessageOutputDebug().Output(msg + wxS('\n'));
476 }
477 else
478 {
479 DoLogText(msg);
480 }
481}
dcc40ba5 482
bc73d5ae
VZ
483void wxLog::DoLogText(const wxString& WXUNUSED(msg))
484{
485 // in 2.8-compatible build the derived class might override DoLog() or
486 // DoLogString() instead so we can't have this assert there
487#if !WXWIN_COMPATIBILITY_2_8
488 wxFAIL_MSG( "must be overridden if it is called" );
489#endif // WXWIN_COMPATIBILITY_2_8
490}
5d88a6b5 491
fbbc4e8f
VZ
492#if WXWIN_COMPATIBILITY_2_8
493
bc73d5ae 494void wxLog::DoLog(wxLogLevel WXUNUSED(level), const char *szString, time_t t)
5d88a6b5 495{
bc73d5ae 496 DoLogString(szString, t);
5d88a6b5
VZ
497}
498
bc73d5ae 499void wxLog::DoLog(wxLogLevel WXUNUSED(level), const wchar_t *wzString, time_t t)
5d88a6b5 500{
bc73d5ae 501 DoLogString(wzString, t);
5d88a6b5
VZ
502}
503
fbbc4e8f
VZ
504#endif // WXWIN_COMPATIBILITY_2_8
505
bc73d5ae
VZ
506// ----------------------------------------------------------------------------
507// wxLog active target management
508// ----------------------------------------------------------------------------
5d88a6b5 509
9ec05cc9
VZ
510wxLog *wxLog::GetActiveTarget()
511{
acad886c
VZ
512#if wxUSE_THREADS
513 if ( !wxThread::IsMain() )
514 {
515 // check if we have a thread-specific log target
516 wxLog * const logger = wxThreadInfo.logger;
517
518 // the code below should be only executed for the main thread as
519 // CreateLogTarget() is not meant for auto-creating log targets for
520 // worker threads so skip it in any case
521 return logger ? logger : ms_pLogger;
522 }
523#endif // wxUSE_THREADS
524
5d7526b0
VZ
525 return GetMainThreadActiveTarget();
526}
527
528/* static */
529wxLog *wxLog::GetMainThreadActiveTarget()
530{
0fb67cd1
VZ
531 if ( ms_bAutoCreate && ms_pLogger == NULL ) {
532 // prevent infinite recursion if someone calls wxLogXXX() from
533 // wxApp::CreateLogTarget()
f644b28c 534 static bool s_bInGetActiveTarget = false;
0fb67cd1 535 if ( !s_bInGetActiveTarget ) {
f644b28c 536 s_bInGetActiveTarget = true;
0fb67cd1 537
0fb67cd1
VZ
538 // ask the application to create a log target for us
539 if ( wxTheApp != NULL )
dc6d5e38 540 ms_pLogger = wxTheApp->GetTraits()->CreateLogTarget();
0fb67cd1 541 else
55b24eb8 542 ms_pLogger = new wxLogOutputBest;
0fb67cd1 543
f644b28c 544 s_bInGetActiveTarget = false;
0fb67cd1
VZ
545
546 // do nothing if it fails - what can we do?
547 }
275bf4c1 548 }
c801d85f 549
0fb67cd1 550 return ms_pLogger;
c801d85f
KB
551}
552
c085e333 553wxLog *wxLog::SetActiveTarget(wxLog *pLogger)
9ec05cc9 554{
0fb67cd1
VZ
555 if ( ms_pLogger != NULL ) {
556 // flush the old messages before changing because otherwise they might
557 // get lost later if this target is not restored
558 ms_pLogger->Flush();
559 }
c801d85f 560
0fb67cd1
VZ
561 wxLog *pOldLogger = ms_pLogger;
562 ms_pLogger = pLogger;
c085e333 563
0fb67cd1 564 return pOldLogger;
c801d85f
KB
565}
566
acad886c
VZ
567#if wxUSE_THREADS
568/* static */
569wxLog *wxLog::SetThreadActiveTarget(wxLog *logger)
570{
571 wxASSERT_MSG( !wxThread::IsMain(), "use SetActiveTarget() for main thread" );
572
573 wxLog * const oldLogger = wxThreadInfo.logger;
574 if ( oldLogger )
575 oldLogger->Flush();
576
577 wxThreadInfo.logger = logger;
578
579 return oldLogger;
580}
581#endif // wxUSE_THREADS
582
36bd6902
VZ
583void wxLog::DontCreateOnDemand()
584{
f644b28c 585 ms_bAutoCreate = false;
36bd6902
VZ
586
587 // this is usually called at the end of the program and we assume that it
588 // is *always* called at the end - so we free memory here to avoid false
589 // memory leak reports from wxWin memory tracking code
590 ClearTraceMasks();
591}
592
e94cd97d
DE
593void wxLog::DoCreateOnDemand()
594{
595 ms_bAutoCreate = true;
596}
597
c602c59b
VZ
598// ----------------------------------------------------------------------------
599// wxLog components levels
600// ----------------------------------------------------------------------------
601
602/* static */
603void wxLog::SetComponentLevel(const wxString& component, wxLogLevel level)
604{
605 if ( component.empty() )
606 {
607 SetLogLevel(level);
608 }
609 else
610 {
611 wxCRIT_SECT_LOCKER(lock, GetLevelsCS());
612
bc1e0d4d 613 GetComponentLevels()[component] = level;
c602c59b
VZ
614 }
615}
616
617/* static */
618wxLogLevel wxLog::GetComponentLevel(wxString component)
619{
620 wxCRIT_SECT_LOCKER(lock, GetLevelsCS());
621
bc1e0d4d 622 const wxStringToNumHashMap& componentLevels = GetComponentLevels();
c602c59b
VZ
623 while ( !component.empty() )
624 {
625 wxStringToNumHashMap::const_iterator
bc1e0d4d
VZ
626 it = componentLevels.find(component);
627 if ( it != componentLevels.end() )
c602c59b
VZ
628 return static_cast<wxLogLevel>(it->second);
629
630 component = component.BeforeLast('/');
631 }
632
633 return GetLogLevel();
634}
635
636// ----------------------------------------------------------------------------
637// wxLog trace masks
638// ----------------------------------------------------------------------------
639
55e5154d
VZ
640namespace
641{
642
643// because IsAllowedTraceMask() may be called during static initialization
644// (this is not recommended but it may still happen, see #11592) we can't use a
645// simple static variable which might be not initialized itself just yet to
646// store the trace masks, but need this accessor function which will ensure
647// that the variable is always correctly initialized before being accessed
648//
649// notice that this doesn't make accessing it MT-safe, of course, you need to
650// serialize accesses to it using GetTraceMaskCS() for this
651wxArrayString& TraceMasks()
652{
653 static wxArrayString s_traceMasks;
654
655 return s_traceMasks;
656}
657
658} // anonymous namespace
659
660/* static */ const wxArrayString& wxLog::GetTraceMasks()
661{
662 // because of this function signature (it returns a reference, not the
663 // object), it is inherently MT-unsafe so there is no need to acquire the
664 // lock here anyhow
665
666 return TraceMasks();
667}
668
f96233d5
VZ
669void wxLog::AddTraceMask(const wxString& str)
670{
766aecab 671 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
f96233d5 672
55e5154d 673 TraceMasks().push_back(str);
f96233d5
VZ
674}
675
0fb67cd1 676void wxLog::RemoveTraceMask(const wxString& str)
c801d85f 677{
766aecab 678 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
f96233d5 679
55e5154d 680 int index = TraceMasks().Index(str);
0fb67cd1 681 if ( index != wxNOT_FOUND )
55e5154d 682 TraceMasks().RemoveAt((size_t)index);
0fb67cd1 683}
c801d85f 684
36bd6902
VZ
685void wxLog::ClearTraceMasks()
686{
766aecab 687 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
f96233d5 688
55e5154d 689 TraceMasks().Clear();
36bd6902
VZ
690}
691
c602c59b
VZ
692/*static*/ bool wxLog::IsAllowedTraceMask(const wxString& mask)
693{
694 wxCRIT_SECT_LOCKER(lock, GetTraceMaskCS());
695
55e5154d
VZ
696 const wxArrayString& masks = GetTraceMasks();
697 for ( wxArrayString::const_iterator it = masks.begin(),
698 en = masks.end();
699 it != en;
700 ++it )
c602c59b
VZ
701 {
702 if ( *it == mask)
703 return true;
704 }
705
706 return false;
707}
708
709// ----------------------------------------------------------------------------
710// wxLog miscellaneous other methods
711// ----------------------------------------------------------------------------
712
4ffdb640
VZ
713#if wxUSE_DATETIME
714
d2e1ef19
VZ
715void wxLog::TimeStamp(wxString *str)
716{
cb296f30 717 if ( !ms_timestamp.empty() )
d2e1ef19 718 {
01904487
VZ
719 *str = wxDateTime::UNow().Format(ms_timestamp);
720 *str += wxS(": ");
d2e1ef19
VZ
721 }
722}
723
4ffdb640
VZ
724void wxLog::TimeStamp(wxString *str, time_t t)
725{
726 if ( !ms_timestamp.empty() )
727 {
728 *str = wxDateTime(t).Format(ms_timestamp);
729 *str += wxS(": ");
730 }
731}
732
733#else // !wxUSE_DATETIME
734
735void wxLog::TimeStamp(wxString*)
736{
737}
738
739void wxLog::TimeStamp(wxString*, time_t)
740{
741}
742
743#endif // wxUSE_DATETIME/!wxUSE_DATETIME
744
232addd1 745#if wxUSE_THREADS
232addd1 746
acad886c
VZ
747void wxLog::FlushThreadMessages()
748{
232addd1
VZ
749 // check if we have queued messages from other threads
750 wxLogRecords bufferedLogRecords;
751
752 {
753 wxCriticalSectionLocker lock(GetBackgroundLogCS());
754 bufferedLogRecords.swap(gs_bufferedLogRecords);
755
756 // release the lock now to not keep it while we are logging the
757 // messages below, allowing background threads to run
758 }
759
760 if ( !bufferedLogRecords.empty() )
761 {
762 for ( wxLogRecords::const_iterator it = bufferedLogRecords.begin();
763 it != bufferedLogRecords.end();
764 ++it )
765 {
acad886c 766 CallDoLogNow(it->level, it->msg, it->info);
232addd1
VZ
767 }
768 }
acad886c
VZ
769}
770
53ff8df7
VZ
771/* static */
772bool wxLog::IsThreadLoggingEnabled()
773{
774 return !wxThreadInfo.loggingDisabled;
775}
776
777/* static */
778bool wxLog::EnableThreadLogging(bool enable)
779{
780 const bool wasEnabled = !wxThreadInfo.loggingDisabled;
781 wxThreadInfo.loggingDisabled = !enable;
782 return wasEnabled;
783}
784
232addd1
VZ
785#endif // wxUSE_THREADS
786
4ffdb640
VZ
787wxLogFormatter *wxLog::SetFormatter(wxLogFormatter* formatter)
788{
789 wxLogFormatter* formatterOld = m_formatter;
790 m_formatter = formatter ? formatter : new wxLogFormatter;
791
792 return formatterOld;
793}
794
acad886c
VZ
795void wxLog::Flush()
796{
6f6b48f1 797 LogLastRepeatIfNeeded();
c801d85f
KB
798}
799
acad886c
VZ
800/* static */
801void wxLog::FlushActive()
802{
803 if ( ms_suspendCount )
804 return;
805
806 wxLog * const log = GetActiveTarget();
807 if ( log )
808 {
809#if wxUSE_THREADS
810 if ( wxThread::IsMain() )
811 log->FlushThreadMessages();
812#endif // wxUSE_THREADS
813
814 log->Flush();
815 }
816}
817
d3fc1755
VZ
818// ----------------------------------------------------------------------------
819// wxLogBuffer implementation
820// ----------------------------------------------------------------------------
821
822void wxLogBuffer::Flush()
823{
232addd1
VZ
824 wxLog::Flush();
825
a23bbe93
VZ
826 if ( !m_str.empty() )
827 {
828 wxMessageOutputBest out;
a0516656 829 out.Printf(wxS("%s"), m_str.c_str());
a23bbe93
VZ
830 m_str.clear();
831 }
d3fc1755
VZ
832}
833
bc73d5ae 834void wxLogBuffer::DoLogTextAtLevel(wxLogLevel level, const wxString& msg)
83250f1a 835{
711f12ef
VZ
836 // don't put debug messages in the buffer, we don't want to show
837 // them to the user in a msg box, log them immediately
bc73d5ae 838 switch ( level )
711f12ef 839 {
bc73d5ae
VZ
840 case wxLOG_Debug:
841 case wxLOG_Trace:
842 wxLog::DoLogTextAtLevel(level, msg);
843 break;
83250f1a 844
bc73d5ae
VZ
845 default:
846 m_str << msg << wxS("\n");
83250f1a
VZ
847 }
848}
849
c801d85f
KB
850// ----------------------------------------------------------------------------
851// wxLogStderr class implementation
852// ----------------------------------------------------------------------------
853
854wxLogStderr::wxLogStderr(FILE *fp)
855{
0fb67cd1
VZ
856 if ( fp == NULL )
857 m_fp = stderr;
858 else
859 m_fp = fp;
c801d85f
KB
860}
861
bc73d5ae 862void wxLogStderr::DoLogText(const wxString& msg)
c801d85f 863{
bc73d5ae 864 wxFputs(msg + '\n', m_fp);
0fb67cd1 865 fflush(m_fp);
1e8a4bc2 866
e2478fde
VZ
867 // under GUI systems such as Windows or Mac, programs usually don't have
868 // stderr at all, so show the messages also somewhere else, typically in
869 // the debugger window so that they go at least somewhere instead of being
870 // simply lost
1ec5cbf3
VZ
871 if ( m_fp == stderr )
872 {
e2478fde
VZ
873 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
874 if ( traits && !traits->HasStderr() )
875 {
bc73d5ae 876 wxMessageOutputDebug().Output(msg + wxS('\n'));
e2478fde 877 }
03147cd0 878 }
c801d85f
KB
879}
880
881// ----------------------------------------------------------------------------
882// wxLogStream implementation
883// ----------------------------------------------------------------------------
884
4bf78aae 885#if wxUSE_STD_IOSTREAM
65f19af1 886#include "wx/ioswrap.h"
dd107c50 887wxLogStream::wxLogStream(wxSTD ostream *ostr)
c801d85f 888{
0fb67cd1 889 if ( ostr == NULL )
dd107c50 890 m_ostr = &wxSTD cerr;
0fb67cd1
VZ
891 else
892 m_ostr = ostr;
c801d85f
KB
893}
894
bc73d5ae 895void wxLogStream::DoLogText(const wxString& msg)
c801d85f 896{
bc73d5ae 897 (*m_ostr) << msg << wxSTD endl;
c801d85f 898}
0fb67cd1 899#endif // wxUSE_STD_IOSTREAM
c801d85f 900
03147cd0
VZ
901// ----------------------------------------------------------------------------
902// wxLogChain
903// ----------------------------------------------------------------------------
904
905wxLogChain::wxLogChain(wxLog *logger)
906{
f644b28c 907 m_bPassMessages = true;
71debe95 908
03147cd0
VZ
909 m_logNew = logger;
910 m_logOld = wxLog::SetActiveTarget(this);
911}
912
199e91fb
VZ
913wxLogChain::~wxLogChain()
914{
a16e51b5 915 wxLog::SetActiveTarget(m_logOld);
e95f8fde
VZ
916
917 if ( m_logNew != this )
918 delete m_logNew;
199e91fb
VZ
919}
920
03147cd0
VZ
921void wxLogChain::SetLog(wxLog *logger)
922{
923 if ( m_logNew != this )
924 delete m_logNew;
925
03147cd0
VZ
926 m_logNew = logger;
927}
928
929void wxLogChain::Flush()
930{
931 if ( m_logOld )
932 m_logOld->Flush();
933
1ec5cbf3 934 // be careful to avoid infinite recursion
03147cd0
VZ
935 if ( m_logNew && m_logNew != this )
936 m_logNew->Flush();
937}
938
bc73d5ae
VZ
939void wxLogChain::DoLogRecord(wxLogLevel level,
940 const wxString& msg,
941 const wxLogRecordInfo& info)
03147cd0
VZ
942{
943 // let the previous logger show it
944 if ( m_logOld && IsPassingMessages() )
bc73d5ae 945 m_logOld->LogRecord(level, msg, info);
03147cd0 946
efce878a 947 // and also send it to the new one
51eb0606
VZ
948 if ( m_logNew )
949 {
950 // don't call m_logNew->LogRecord() to avoid infinite recursion when
951 // m_logNew is this object itself
952 if ( m_logNew != this )
953 m_logNew->LogRecord(level, msg, info);
954 else
955 wxLog::DoLogRecord(level, msg, info);
956 }
03147cd0
VZ
957}
958
93d4c1d0
VZ
959#ifdef __VISUALC__
960 // "'this' : used in base member initializer list" - so what?
961 #pragma warning(disable:4355)
962#endif // VC++
963
47fe7ff3
JS
964// ----------------------------------------------------------------------------
965// wxLogInterposer
966// ----------------------------------------------------------------------------
967
968wxLogInterposer::wxLogInterposer()
969 : wxLogChain(this)
970{
971}
972
973// ----------------------------------------------------------------------------
974// wxLogInterposerTemp
975// ----------------------------------------------------------------------------
976
977wxLogInterposerTemp::wxLogInterposerTemp()
93d4c1d0
VZ
978 : wxLogChain(this)
979{
766aecab 980 DetachOldLog();
93d4c1d0
VZ
981}
982
983#ifdef __VISUALC__
984 #pragma warning(default:4355)
985#endif // VC++
986
c801d85f
KB
987// ============================================================================
988// Global functions/variables
989// ============================================================================
990
991// ----------------------------------------------------------------------------
992// static variables
993// ----------------------------------------------------------------------------
0fb67cd1 994
f9837791 995bool wxLog::ms_bRepetCounting = false;
f9837791 996
d3b9f782 997wxLog *wxLog::ms_pLogger = NULL;
f644b28c
WS
998bool wxLog::ms_doLog = true;
999bool wxLog::ms_bAutoCreate = true;
1000bool wxLog::ms_bVerbose = false;
d2e1ef19 1001
edc73852
RD
1002wxLogLevel wxLog::ms_logLevel = wxLOG_Max; // log everything by default
1003
2ed3265e
VZ
1004size_t wxLog::ms_suspendCount = 0;
1005
a0516656 1006wxString wxLog::ms_timestamp(wxS("%X")); // time only, no date
d2e1ef19 1007
34085a0d 1008#if WXWIN_COMPATIBILITY_2_8
0fb67cd1 1009wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
34085a0d
VZ
1010#endif // wxDEBUG_LEVEL
1011
c801d85f
KB
1012// ----------------------------------------------------------------------------
1013// stdout error logging helper
1014// ----------------------------------------------------------------------------
1015
1016// helper function: wraps the message and justifies it under given position
1017// (looks more pretty on the terminal). Also adds newline at the end.
1018//
0fb67cd1
VZ
1019// TODO this is now disabled until I find a portable way of determining the
1020// terminal window size (ok, I found it but does anybody really cares?)
1021#ifdef LOG_PRETTY_WRAP
c801d85f
KB
1022static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
1023{
0fb67cd1
VZ
1024 size_t nMax = 80; // FIXME
1025 size_t nStart = strlen(pszPrefix);
1026 fputs(pszPrefix, f);
1027
1028 size_t n;
1029 while ( *psz != '\0' ) {
1030 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
1031 putc(*psz++, f);
1032
1033 // wrapped?
1034 if ( *psz != '\0' ) {
1035 /*putc('\n', f);*/
1036 for ( n = 0; n < nStart; n++ )
1037 putc(' ', f);
1038
1039 // as we wrapped, squeeze all white space
1040 while ( isspace(*psz) )
1041 psz++;
1042 }
c801d85f 1043 }
c801d85f 1044
0fb67cd1 1045 putc('\n', f);
c801d85f
KB
1046}
1047#endif //LOG_PRETTY_WRAP
1048
1049// ----------------------------------------------------------------------------
1050// error code/error message retrieval functions
1051// ----------------------------------------------------------------------------
1052
1053// get error code from syste
1054unsigned long wxSysErrorCode()
1055{
8cb172b4 1056#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
0fb67cd1 1057 return ::GetLastError();
0fb67cd1 1058#else //Unix
c801d85f 1059 return errno;
0fb67cd1 1060#endif //Win/Unix
c801d85f
KB
1061}
1062
1063// get error message from system
50920146 1064const wxChar *wxSysErrorMsg(unsigned long nErrCode)
c801d85f 1065{
0fb67cd1
VZ
1066 if ( nErrCode == 0 )
1067 nErrCode = wxSysErrorCode();
1068
8cb172b4 1069#if defined(__WXMSW__) && !defined(__WXMICROWIN__)
2e7f3845 1070 static wxChar s_szBuf[1024];
0fb67cd1
VZ
1071
1072 // get error message from system
1073 LPVOID lpMsgBuf;
d0822e56
VZ
1074 if ( ::FormatMessage
1075 (
1076 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
1077 NULL,
1078 nErrCode,
0fb67cd1
VZ
1079 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1080 (LPTSTR)&lpMsgBuf,
d0822e56
VZ
1081 0,
1082 NULL
1083 ) == 0 )
1084 {
1085 // if this happens, something is seriously wrong, so don't use _() here
1086 // for safety
a0516656 1087 wxSprintf(s_szBuf, wxS("unknown error %lx"), nErrCode);
c4b401b6 1088 return s_szBuf;
d0822e56
VZ
1089 }
1090
0fb67cd1
VZ
1091
1092 // copy it to our buffer and free memory
d0822e56 1093 // Crashes on SmartPhone (FIXME)
0c44ec97 1094#if !defined(__SMARTPHONE__) /* of WinCE */
7448de8d
WS
1095 if( lpMsgBuf != 0 )
1096 {
e408bf52 1097 wxStrlcpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf));
251244a0
VZ
1098
1099 LocalFree(lpMsgBuf);
1100
1101 // returned string is capitalized and ended with '\r\n' - bad
1102 s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
1103 size_t len = wxStrlen(s_szBuf);
1104 if ( len > 0 ) {
1105 // truncate string
a0516656
VZ
1106 if ( s_szBuf[len - 2] == wxS('\r') )
1107 s_szBuf[len - 2] = wxS('\0');
251244a0
VZ
1108 }
1109 }
a9928e9d 1110 else
2e7f3845 1111#endif // !__SMARTPHONE__
a9928e9d 1112 {
a0516656 1113 s_szBuf[0] = wxS('\0');
0fb67cd1
VZ
1114 }
1115
1116 return s_szBuf;
2e7f3845
VZ
1117#else // !__WXMSW__
1118 #if wxUSE_UNICODE
1119 static wchar_t s_wzBuf[1024];
1120 wxConvCurrent->MB2WC(s_wzBuf, strerror((int)nErrCode),
1121 WXSIZEOF(s_wzBuf) - 1);
1122 return s_wzBuf;
1123 #else
1124 return strerror((int)nErrCode);
1125 #endif
1126#endif // __WXMSW__/!__WXMSW__
c801d85f
KB
1127}
1128
e2478fde 1129#endif // wxUSE_LOG