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