]> git.saurik.com Git - wxWidgets.git/blame - src/common/log.cpp
Use correct extensions in wxDynamicLibrary::CanonicalizeName() on OS X.
[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 904 m_logNew = logger;
1cdaa5f2
VZ
905
906 // Notice that we use GetActiveTarget() here instead of directly calling
907 // SetActiveTarget() to trigger wxLog auto-creation: if we're created as
908 // the first logger, we should still chain with the standard, implicit and
909 // possibly still not created standard logger instead of disabling normal
910 // logging entirely.
911 m_logOld = wxLog::GetActiveTarget();
912 wxLog::SetActiveTarget(this);
03147cd0
VZ
913}
914
199e91fb
VZ
915wxLogChain::~wxLogChain()
916{
a16e51b5 917 wxLog::SetActiveTarget(m_logOld);
e95f8fde
VZ
918
919 if ( m_logNew != this )
920 delete m_logNew;
199e91fb
VZ
921}
922
03147cd0
VZ
923void wxLogChain::SetLog(wxLog *logger)
924{
925 if ( m_logNew != this )
926 delete m_logNew;
927
03147cd0
VZ
928 m_logNew = logger;
929}
930
931void wxLogChain::Flush()
932{
933 if ( m_logOld )
934 m_logOld->Flush();
935
1ec5cbf3 936 // be careful to avoid infinite recursion
03147cd0
VZ
937 if ( m_logNew && m_logNew != this )
938 m_logNew->Flush();
939}
940
bc73d5ae
VZ
941void wxLogChain::DoLogRecord(wxLogLevel level,
942 const wxString& msg,
943 const wxLogRecordInfo& info)
03147cd0
VZ
944{
945 // let the previous logger show it
946 if ( m_logOld && IsPassingMessages() )
bc73d5ae 947 m_logOld->LogRecord(level, msg, info);
03147cd0 948
efce878a 949 // and also send it to the new one
51eb0606
VZ
950 if ( m_logNew )
951 {
952 // don't call m_logNew->LogRecord() to avoid infinite recursion when
953 // m_logNew is this object itself
954 if ( m_logNew != this )
955 m_logNew->LogRecord(level, msg, info);
956 else
957 wxLog::DoLogRecord(level, msg, info);
958 }
03147cd0
VZ
959}
960
93d4c1d0
VZ
961#ifdef __VISUALC__
962 // "'this' : used in base member initializer list" - so what?
963 #pragma warning(disable:4355)
964#endif // VC++
965
47fe7ff3
JS
966// ----------------------------------------------------------------------------
967// wxLogInterposer
968// ----------------------------------------------------------------------------
969
970wxLogInterposer::wxLogInterposer()
971 : wxLogChain(this)
972{
973}
974
975// ----------------------------------------------------------------------------
976// wxLogInterposerTemp
977// ----------------------------------------------------------------------------
978
979wxLogInterposerTemp::wxLogInterposerTemp()
93d4c1d0
VZ
980 : wxLogChain(this)
981{
766aecab 982 DetachOldLog();
93d4c1d0
VZ
983}
984
985#ifdef __VISUALC__
986 #pragma warning(default:4355)
987#endif // VC++
988
c801d85f
KB
989// ============================================================================
990// Global functions/variables
991// ============================================================================
992
993// ----------------------------------------------------------------------------
994// static variables
995// ----------------------------------------------------------------------------
0fb67cd1 996
f9837791 997bool wxLog::ms_bRepetCounting = false;
f9837791 998
d3b9f782 999wxLog *wxLog::ms_pLogger = NULL;
f644b28c
WS
1000bool wxLog::ms_doLog = true;
1001bool wxLog::ms_bAutoCreate = true;
1002bool wxLog::ms_bVerbose = false;
d2e1ef19 1003
edc73852
RD
1004wxLogLevel wxLog::ms_logLevel = wxLOG_Max; // log everything by default
1005
2ed3265e
VZ
1006size_t wxLog::ms_suspendCount = 0;
1007
a0516656 1008wxString wxLog::ms_timestamp(wxS("%X")); // time only, no date
d2e1ef19 1009
34085a0d 1010#if WXWIN_COMPATIBILITY_2_8
0fb67cd1 1011wxTraceMask wxLog::ms_ulTraceMask = (wxTraceMask)0;
34085a0d
VZ
1012#endif // wxDEBUG_LEVEL
1013
c801d85f
KB
1014// ----------------------------------------------------------------------------
1015// stdout error logging helper
1016// ----------------------------------------------------------------------------
1017
1018// helper function: wraps the message and justifies it under given position
1019// (looks more pretty on the terminal). Also adds newline at the end.
1020//
0fb67cd1
VZ
1021// TODO this is now disabled until I find a portable way of determining the
1022// terminal window size (ok, I found it but does anybody really cares?)
1023#ifdef LOG_PRETTY_WRAP
c801d85f
KB
1024static void wxLogWrap(FILE *f, const char *pszPrefix, const char *psz)
1025{
0fb67cd1
VZ
1026 size_t nMax = 80; // FIXME
1027 size_t nStart = strlen(pszPrefix);
1028 fputs(pszPrefix, f);
1029
1030 size_t n;
1031 while ( *psz != '\0' ) {
1032 for ( n = nStart; (n < nMax) && (*psz != '\0'); n++ )
1033 putc(*psz++, f);
1034
1035 // wrapped?
1036 if ( *psz != '\0' ) {
1037 /*putc('\n', f);*/
1038 for ( n = 0; n < nStart; n++ )
1039 putc(' ', f);
1040
1041 // as we wrapped, squeeze all white space
1042 while ( isspace(*psz) )
1043 psz++;
1044 }
c801d85f 1045 }
c801d85f 1046
0fb67cd1 1047 putc('\n', f);
c801d85f
KB
1048}
1049#endif //LOG_PRETTY_WRAP
1050
1051// ----------------------------------------------------------------------------
1052// error code/error message retrieval functions
1053// ----------------------------------------------------------------------------
1054
1055// get error code from syste
1056unsigned long wxSysErrorCode()
1057{
d98a58c5 1058#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
0fb67cd1 1059 return ::GetLastError();
0fb67cd1 1060#else //Unix
c801d85f 1061 return errno;
0fb67cd1 1062#endif //Win/Unix
c801d85f
KB
1063}
1064
1065// get error message from system
50920146 1066const wxChar *wxSysErrorMsg(unsigned long nErrCode)
c801d85f 1067{
0fb67cd1
VZ
1068 if ( nErrCode == 0 )
1069 nErrCode = wxSysErrorCode();
1070
d98a58c5 1071#if defined(__WINDOWS__) && !defined(__WXMICROWIN__)
2e7f3845 1072 static wxChar s_szBuf[1024];
0fb67cd1
VZ
1073
1074 // get error message from system
1075 LPVOID lpMsgBuf;
d0822e56
VZ
1076 if ( ::FormatMessage
1077 (
1078 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
1079 NULL,
1080 nErrCode,
0fb67cd1
VZ
1081 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1082 (LPTSTR)&lpMsgBuf,
d0822e56
VZ
1083 0,
1084 NULL
1085 ) == 0 )
1086 {
1087 // if this happens, something is seriously wrong, so don't use _() here
1088 // for safety
a0516656 1089 wxSprintf(s_szBuf, wxS("unknown error %lx"), nErrCode);
c4b401b6 1090 return s_szBuf;
d0822e56
VZ
1091 }
1092
0fb67cd1
VZ
1093
1094 // copy it to our buffer and free memory
d0822e56 1095 // Crashes on SmartPhone (FIXME)
0c44ec97 1096#if !defined(__SMARTPHONE__) /* of WinCE */
7448de8d
WS
1097 if( lpMsgBuf != 0 )
1098 {
e408bf52 1099 wxStrlcpy(s_szBuf, (const wxChar *)lpMsgBuf, WXSIZEOF(s_szBuf));
251244a0
VZ
1100
1101 LocalFree(lpMsgBuf);
1102
1103 // returned string is capitalized and ended with '\r\n' - bad
1104 s_szBuf[0] = (wxChar)wxTolower(s_szBuf[0]);
1105 size_t len = wxStrlen(s_szBuf);
1106 if ( len > 0 ) {
1107 // truncate string
a0516656
VZ
1108 if ( s_szBuf[len - 2] == wxS('\r') )
1109 s_szBuf[len - 2] = wxS('\0');
251244a0
VZ
1110 }
1111 }
a9928e9d 1112 else
2e7f3845 1113#endif // !__SMARTPHONE__
a9928e9d 1114 {
a0516656 1115 s_szBuf[0] = wxS('\0');
0fb67cd1
VZ
1116 }
1117
1118 return s_szBuf;
d98a58c5 1119#else // !__WINDOWS__
2e7f3845
VZ
1120 #if wxUSE_UNICODE
1121 static wchar_t s_wzBuf[1024];
1122 wxConvCurrent->MB2WC(s_wzBuf, strerror((int)nErrCode),
1123 WXSIZEOF(s_wzBuf) - 1);
1124 return s_wzBuf;
1125 #else
1126 return strerror((int)nErrCode);
1127 #endif
d98a58c5 1128#endif // __WINDOWS__/!__WINDOWS__
c801d85f
KB
1129}
1130
e2478fde 1131#endif // wxUSE_LOG