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