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