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