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