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