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