Debian Codegraph @

src/Base/Console.h

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /***************************************************************************
4 * Copyright (c) 2002 Jürgen Riegel <[email protected]> *
5 * *
6 * This file is part of the FreeCAD CAx development system. *
7 * *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU Library General Public License (LGPL) *
10 * as published by the Free Software Foundation; either version 2 of *
11 * the License, or (at your option) any later version. *
12 * for detail see the LICENCE text file. *
13 * *
14 * FreeCAD is distributed in the hope that it will be useful, *
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
17 * GNU Library General Public License for more details. *
18 * *
19 * You should have received a copy of the GNU Library General Public *
20 * License along with FreeCAD; if not, write to the Free Software *
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
22 * USA *
23 * *
24 ***************************************************************************/
25
26 #ifndef BASE_CONSOLE_H
27 #define BASE_CONSOLE_H
28
29 // Std. configurations
30 #include <array>
31 #include <cassert>
32 #include <chrono>
33 #include <map>
34 #include <set>
35 #include <string>
36 #include <sstream>
37 #include <FCGlobal.h>
38
39 #include <fmt/printf.h>
40
41 // Python stuff
42 using PyObject = struct _object;
43 using PyMethodDef = struct PyMethodDef;
44
45 // FIXME: Even with parameter packs this is necessary for MSYS2
46 #if defined(__clang__)
47 # pragma clang diagnostic push
48 # pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
49 #endif
50
51 //**************************************************************************
52 // Logging levels
53
54 #ifdef FC_DEBUG
55 /// switch on the logging of python object creation and destruction
56 # undef FC_LOGPYOBJECTS
57 /// switch on the logging of Feature update and execution
58 # define FC_LOGFEATUREUPDATE
59 /// switch on the logging of the Update execution through Doc, App, GuiApp and GuiDoc
60 # undef FC_LOGUPDATECHAIN
61 #endif
62
63 /////////////////////////////////////////////////////////////////////////////////////
64
65 /** \page LogLevelPage Tag based log helpers
66 * Simple tag based log and timing helper macros and functions.
67 *
68 * \section Motivation
69 *
70 * FreeCAD Base::Console() is capable of outputting to different targets, and has
71 * some basic enable/disable control of different types of logs. There is,
72 * however, no easy way to use logging facility for various FC modules. This set
73 * of helper macros and function is aimed to provide a unified logging (and timing)
74 * interface. The interface is mainly designed for C++ code. Python code can
75 * also take some advantage of log level control interface. The developer can
76 * now leave their logging code permanently active in the source code without
77 * impact on performance, and the log can be easily turned on/off dynamically
78 * using Python console for debugging purpose, even in release build.
79 *
80 * \section SampleUsage Sample Usage
81 *
82 * A set of macros is provided to ease the usage of tag based log. All the
83 * macros are defined in <Base/Console.h>. At the beginning of your C++ source,
84 * you need to initialize the log level of your chosen tag using,
85 *
86 * \code{.c}
87 * FC_LOG_LEVEL_INIT(tag)
88 * \endcode
89 *
90 * It makes sense to use the same tag in multiple files for easy log level
91 * control. Please check \ref Customization if You want more than one tag inside
92 * the same source file.
93 *
94 * Predefined log levels are,
95 *
96 * \code{.c}
97 * #define FC_LOGLEVEL_ERR 0
98 * #define FC_LOGLEVEL_WARN 1
99 * #define FC_LOGLEVEL_MSG 2
100 * #define FC_LOGLEVEL_LOG 3
101 * #define FC_LOGLEVEL_TRACE 4
102 * \endcode
103 *
104 * Bigger log level integer values have lower priorities. There is a special log
105 * level,
106 *
107 * \code{.c}
108 * #define FC_LOGLEVEL_DEFAULT -1
109 * \endcode
110 *
111 * Actually, any negative log level behave the same, which is for tags
112 * that are not previously configured by user. The actual log level applied is
113 * controlled by \c Base::Console().SetDefaultLogLevel(). Python
114 * developers/end-users can configure the default log level by calling
115 *
116 * \code{.py}
117 * FreeCAD.setLogLevel('Default',level)
118 * FreeCAD.setLogLevel('DebugDefault',level)
119 * \endcode
120 *
121 * where \c level is either a string of value <tt>Error, Warning, Message, Log,
122 * Trace</tt> or an integer value. By default, on release build, the default log
123 * level is \c FC_LOGLEVEL_MSG, and on debug build, \c FC_LOGLEVEL_LOG.
124 *
125 * Python code can call \c FreeCAD.setLogLevel(tag,level) to configure any other
126 * tag log levels, and \c FreeCAD.getLogLevel(tag), which outputs only integer
127 * log level.
128 *
129 * You can fine tune how the log is output by passing extra parameters to
130 * #FC_LOG_LEVEL_INIT(). All the extra parameters are boolean value, which are
131 * shown blew along with their default values.
132 *
133 * \code{.c}
134 * FC_LOG_LEVEL_INIT(tag, print_tag=true, print_src=0,
135 * print_time=false, add_eol=true, refresh=false)
136 * \endcode
137 *
138 * You can dynamically modify the log style as well, by changing these
139 * variables before the actual log output macro. See \ref Customization for
140 * more details
141 *
142 * \code{.c}
143 * FC_LOG_INSTANCE.refresh = true; // print time for each log, default false.
144 *
145 * // print file and line number, default 0, if set to 2 then print python
146 * // source from current call frame.
147 * FC_LOG_INSTANCE.print_src = 1;
148 *
149 * FC_LOG_INSTANCE.print_tag = false; // do not print tag, default true
150 * FC_LOG_INSTANCE.add_eol = false; // do not add eol
151 * FC_LOG_INSTANCE.refresh = true; // refresh GUI after each log
152 * \endcode
153 *
154 * Be careful with 'refresh' option. Its current implementation calls
155 * QCoreApplication::sendPostedEvent() which may cause some unexpected
156 * behavior, especially when called inside a destructor.
157 *
158 * The actual logging macros are
159 *
160 * \code
161 * FC_ERR(msg)
162 * FC_WARN(msg)
163 * FC_MSG(msg)
164 * FC_LOG(msg)
165 * FC_TRACE(msg)
166 * \endcode
167 *
168 * The logging macros correspond to existing Base::Console() output functions,
169 * and \c FC_TRACE uses Base::Console().Log(), same as \c FC_LOG. These macros
170 * checks the log level defined in \c FC_LOG_LEVEL_INIT to decide whether to
171 * print log or not. \c msg here shall be a C++ streaming expression. End of
172 * line will be automatically appended by default.
173 *
174 * \code
175 * FC_ERR("error: " << code << ". exiting")
176 * \endcode
177 *
178 * \section TimingHelper Timing Helpers
179 *
180 * This set of macros is for helping C++ code to time lengthy operations.
181 * Examples:
182 *
183 * \code{.c}
184 * void operation() {
185 * FC_TIME_INIT(t);
186 *
187 * //do stuff
188 *
189 * FC_TIME_LOG(t,"operation done.");
190 * }
191 * \endcode
192 *
193 * This will output in console something like,
194 *
195 * \code
196 * operation done. time: 1.12s
197 * \endcode
198 *
199 * Every time you call \c FC_TIME_LOG it will calculate the time duration
200 * between this call and the last \c FC_TIME_LOG or \c FC_TIME_INIT. Time
201 * variable \c t will then be updated to the current time. You can also use
202 * <tt>FC_TIME_MSG, FC_TIME_TRACE</tt> similar to <tt>FC_MSG and FC_TRACE</tt>.
203 *
204 * To time operation in multiple stages,
205 *
206 * \code{.cpp}
207 * void operation() {
208 * FC_TIME_INIT2(t,t1);
209 *
210 * //do stage 1
211 *
212 * FC_TIME_LOG(t1,"stage1");
213 *
214 * //do stage 2
215 *
216 * FC_TIME_LOG(t1,"stage2");
217 *
218 * // do other stuff
219 *
220 * FC_TIME_LOG(t,"total");
221 * }
222 * \endcode
223 *
224 * Will output something like,
225 * \code
226 * stage1 time: 1.2s
227 * stage2 time: 2.3s
228 * total time: 4.0s
229 * \endcode
230 *
231 * To time operation in multiple functions,
232 *
233 * \code{.cpp}
234 * class Timing {
235 * FC_DURATION_DECLARE(d1)
236 * FC_DURATION_DECLARE(d1_1)
237 * FC_DURATION_DECLARE(d1_2)
238 * FC_DURATION_DECLARE(d2);
239 *
240 * Timing() {
241 * FC_DURATION_INIT(d1);
242 * FC_DURATION_INIT(d1_1);
243 * FC_DURATION_INIT(d1_2);
244 * FC_DURATION_INIT(d2);
245 * }
246 * };
247 *
248 * void operation1(Timing &timing) {
249 *
250 * FC_TIME_INIT(t);
251 *
252 * for(...) {
253 * FC_TIME_INIT(t1);
254 *
255 * //do setp 1
256 *
257 * FC_DURATION_PLUS(timing.d1_1,t1);
258 *
259 * // do step 2
260 *
261 * FC_DURATION_PLUS(timing.d1_2,t1);
262 * }
263 *
264 * // do other stuff
265 *
266 * FC_DRUATION_PLUS(timing.d1, t);
267 * }
268 *
269 * void operation2(Timing &timing) {
270 *
271 * FC_TIME_INIT(t);
272 *
273 * // do stuff
274 *
275 * FC_DRUATION_PLUS(timing.d2, t);
276 * }
277 *
278 * void operation() {
279 *
280 * Timing timing;
281 *
282 * FC_TIME_INIT(t);
283 *
284 * for(...) {
285 * operation1(timing);
286 *
287 * // do other stuff
288 *
289 * operation2(timing);
290 * }
291 *
292 * FC_DURATION_LOG(timing.d1_1,"operation 1 step 1");
293 * FC_DURATION_LOG(timing.d1_2,"operation 1 step 2");
294 * FC_DURATION_LOG(timing.d1,"operation 1");
295 * FC_DURATION_LOG(timing.d2,"operation 2");
296 * FC_TIME_LOG(t,"operation total");
297 * }
298 * \endcode
299 *
300 * You can also use <tt>FC_DURATION_MSG, FC_DURATION_TRACE</tt> as usual.
301 *
302 * If you use only macros provided here to do timing, the entire timing code
303 * can be compiled out by defining \c FC_LOG_NO_TIMING before including
304 * \c App/Console.h.
305 *
306 * \section Customization
307 *
308 * Most of the logging facilities are exposed through macros. This section
309 * briefs how they are implemented under the hood in case you want
310 * customization. A new function GetLogLevel(tag) is added to Base::Console()
311 * to let C++ developer query a log level for an arbitrary string tag. The
312 * function returns a pointer to an integer representing the log level. Python
313 * developer or end-user can set/get the same tag based log level using
314 * FreeCAD.setLogLevel/getLogLevel. Any change to the log level is reflected
315 * through the pointer returned by Base::Console().GetLogLevel(). What
316 * \c FC_LOG_LEVEL_INIT(tag) does is to define a class Base::LogLevel, and then
317 * a file static instance of that class to store the pointer to the desired tag
318 * log level. The class and instance name is predefined. Various log macros
319 * will check that instance to query log level. If you some how want to have
320 * more than one tag inside the same source file, use the following macros to
321 * define a second instance of name \c instance_name
322 *
323 * \code
324 * _FC_LOG_LEVEL_INIT(instance_name,tag)
325 * \endcode
326 *
327 * Then, define a second set of logging macros as
328 *
329 * \code{.c}
330 * #define MY_MSG(_msg) _FC_PRINT(instance_name,FC_LOGLEVEL_MSG,Message,_msg)
331 * #define MY_WARN(_msg) _FC_PRINT(instance_name,FC_LOGLEVEL_WARN,Warning,_msg)
332 * #define MY_ERR(_msg) _FC_PRINT(instance_name,FC_LOGLEVEL_ERR,Error,_msg)
333 * #define MY_LOG(_msg) _FC_PRINT(instance_name,FC_LOGLEVEL_LOG,Log,_msg)
334 * #define MY_TRACE(_msg) _FC_PRINT(instance_name,FC_LOGLEVEL_TRACE,Log,_msg)
335 * \endcode
336 *
337 * Note, replace \c instance_name with your actual desired name.
338 *
339 * You can also define your own log levels the same way. Macro
340 * #_FC_PRINT(_instance,_l,_func,_msg) checks to see if the log shall proceed,
341 * where \c _instance is the static loglevel instance name (default is
342 * \c FC_LOG_INSTANCE), and \c _l is the log level constant to be checked,
343 * \c _func is the Base::Console() function to print the log.
344 *
345 */
346
347 // NOLINTBEGIN(bugprone-reserved-identifier,bugprone-macro-parentheses,cppcoreguidelines-macro-usage,cppcoreguidelines-avoid-do-while)
348 // clang-format off
349 #define FC_LOGLEVEL_DEFAULT -1
350 #define FC_LOGLEVEL_ERR 0
351 #define FC_LOGLEVEL_WARN 1
352 #define FC_LOGLEVEL_MSG 2
353 #define FC_LOGLEVEL_LOG 3
354 #define FC_LOGLEVEL_TRACE 4
355
356 #define _FC_LOG_LEVEL_INIT(_name, _tag, ...) static Base::LogLevel _name(_tag, ##__VA_ARGS__);
357
358 #ifndef FC_LOG_INSTANCE
359 #define FC_LOG_INSTANCE _s_fclvl
360 #endif
361
362 #define FC_LOG_LEVEL_INIT(_tag, ...) _FC_LOG_LEVEL_INIT(FC_LOG_INSTANCE, _tag, ##__VA_ARGS__)
363
364 #define __FC_PRINT(_instance, _l, _func, _notifier, _msg, _file, _line) \
365 do { \
366 if (_instance.isEnabled(_l)) { \
367 std::stringstream _str; \
368 _instance.prefix(_str, _file, _line) << _msg; \
369 if (_instance.add_eol) \
370 _str << '\n'; \
371 Base::Console()._func(_notifier, _str.str().c_str()); \
372 if (_instance.refresh) \
373 Base::Console().refresh(); \
374 } \
375 } while (0)
376
377 #define _FC_PRINT(_instance, _l, _func, _msg) \
378 __FC_PRINT(_instance, _l, _func, std::string(), _msg, __FILE__, __LINE__)
379
380 #define FC_MSG(_msg) _FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_MSG, message, _msg)
381 #define FC_WARN(_msg) _FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_WARN, developerWarning, _msg)
382 #define FC_ERR(_msg) _FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_ERR, developerError, _msg)
383 #define FC_LOG(_msg) _FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_LOG, log, _msg)
384 #define FC_TRACE(_msg) _FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_TRACE, log, _msg)
385
386 #define _FC_MSG(_file, _line, _msg) \
387 __FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_MSG, message, std::string(), _msg, _file, _line)
388 #define _FC_WARN(_file, _line, _msg) \
389 __FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_WARN, developerWarning, std::string(), _msg, _file, _line)
390 #define _FC_ERR(_file, _line, _msg) \
391 __FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_ERR, developerError, std::string(), _msg, _file, _line)
392 #define _FC_LOG(_file, _line, _msg) \
393 __FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_LOG, log, std::string(), _msg, _file, _line)
394 #define _FC_TRACE(_file, _line, _msg) \
395 __FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_TRACE, log, std::string(), _msg, _file, _line)
396
397 #define FC_XYZ(_pt) '(' << (_pt).X() << ", " << (_pt).Y() << ", " << (_pt).Z() << ')'
398 #define FC_xy(_pt) '(' << (_pt).x << ", " << (_pt).y << ')'
399 #define FC_xyz(_pt) '(' << (_pt).x << ", " << (_pt).y << ", " << (_pt).z << ')'
400
401 #ifndef FC_LOG_NO_TIMING
402 #define FC_TIME_CLOCK high_resolution_clock
403 #define FC_TIME_POINT std::chrono::FC_TIME_CLOCK::time_point
404 #define FC_DURATION std::chrono::duration<double>
405
406 #define _FC_TIME_INIT(_t) _t = std::chrono::FC_TIME_CLOCK::now()
407 #define FC_TIME_INIT(_t) FC_TIME_POINT _FC_TIME_INIT(_t)
408 #define FC_TIME_INIT2(_t1, _t2) FC_TIME_INIT(_t1), _t2 = _t1
409 #define FC_TIME_INIT3(_t1, _t2, _t3) FC_TIME_INIT(_t1), _t2 = _t1, _t3 = _t1
410
411 #define _FC_DURATION_PRINT(_l, _d, _msg) FC_##_l(_msg << " time: " << _d.count() << 's');
412
413 #define FC_DURATION_MSG(_d, _msg) _FC_DURATION_PRINT(MSG, _d, _msg)
414 #define FC_DURATION_LOG(_d, _msg) _FC_DURATION_PRINT(LOG, _d, _msg)
415 #define FC_DURATION_TRACE(_d, _msg) _FC_DURATION_PRINT(TRACE, _d, _msg)
416
417 #define _FC_TIME_PRINT(_l, _t, _msg) _FC_DURATION_PRINT(_l, Base::GetDuration(_t), _msg);
418
419 #define FC_TIME_MSG(_t, _msg) _FC_TIME_PRINT(MSG, _t, _msg)
420 #define FC_TIME_LOG(_t, _msg) _FC_TIME_PRINT(LOG, _t, _msg)
421 #define FC_TIME_TRACE(_t, _msg) _FC_TIME_PRINT(TRACE, _t, _msg)
422
423 #define FC_DURATION_DECLARE(_d) FC_DURATION _d
424 #define FC_DURATION_DECLARE2(_d, _d1) FC_DURATION_DECLARE(_d), _d1
425 #define FC_DURATION_DECLARE3(_d, _d1) FC_DURATION_DECLARE2(_d, _d1), _d2
426
427 #define FC_DURATION_INIT(_d) _d = FC_DURATION(0)
428 #define FC_DURATION_INIT2(_d, _d1) _d = _d1 = FC_DURATION(0)
429 #define FC_DURATION_INIT3(_d, _d1, _d2) _d = _d1 = _d2 = FC_DURATION(0)
430
431 #define FC_DURATION_DECL_INIT(_d) FC_DURATION _d(0)
432 #define FC_DURATION_DECL_INIT2(_d, _d1) FC_DURATION_DECL_INIT(_d), _d1(0)
433 #define FC_DURATION_DECL_INIT3(_d, _d1) FC_DURATION_DECL_INIT2(_d, _d1), _d3(0)
434
435 #define FC_DURATION_PLUS(_d, _t) _d += Base::GetDuration(_t)
436
437 #else // FC_LOG_NO_TIMING
438 #define FC_TIME_POINT
439 #define _FC_TIME_INIT(...) \
440 do { \
441 } while (0)
442 #define FC_TIME_INIT(...) \
443 do { \
444 } while (0)
445 #define FC_TIME_INIT2(...) \
446 do { \
447 } while (0)
448 #define FC_TIME_INIT3(...) \
449 do { \
450 } while (0)
451 #define _FC_DURATION_PRINT(...) \
452 do { \
453 } while (0)
454 #define _FC_TIME(_t) \
455 do { \
456 } while (0)
457 #define FC_DURATION_PRINT(...) \
458 do { \
459 } while (0)
460 #define FC_DURATION
461 #define FC_DURATION_INIT(...) \
462 do { \
463 } while (0)
464 #define FC_DURATION_INIT1(...) \
465 do { \
466 } while (0)
467 #define FC_DURATION_INIT2(...) \
468 do { \
469 } while (0)
470 #define FC_DURATION_DECLARE(...)
471 #define FC_DURATION_DECLARE1(...)
472 #define FC_DURATION_DECLARE2(...)
473 #define FC_DURATION_DECL_INIT(...) \
474 do { \
475 } while (0)
476 #define FC_DURATION_DECL_INIT2(...) \
477 do { \
478 } while (0)
479 #define FC_DURATION_DECL_INIT3(...) \
480 do { \
481 } while (0)
482 #define FC_DURATION_PLUS(...) \
483 do { \
484 } while (0)
485
486 #endif // FC_LOG_NO_TIMING
487 // clang-format on
488 // NOLINTEND(bugprone-reserved-identifier,bugprone-macro-parentheses,cppcoreguidelines-macro-usage,cppcoreguidelines-avoid-do-while)
489
490 using ConsoleMsgFlags = unsigned int;
491
492 namespace Base
493 {
494
495 #ifndef FC_LOG_NO_TIMING
496 inline FC_DURATION GetDuration(FC_TIME_POINT& tp)
497 {
498 const auto tnow = std::chrono::FC_TIME_CLOCK::now();
499 const auto dc = std::chrono::duration_cast<FC_DURATION>(tnow - tp);
500 tp = tnow;
501 return dc;
502 }
503 #endif
504
505 /** Used to identify log level*/
506 enum class LogStyle
507 {
508 Warning,
509 Message,
510 Error,
511 Log,
512 Critical, // Special message to mark critical notifications
513 Notification, // Special message for notifications to the user (e.g. educational)
514 };
515
516 /** Used to indicate the intended recipient of a message (warning, error, ...).
517 While it is possible to create a custom message via Console().Send, console provides convenience
518 functions for most common combinations.
519
520 See documentation of ConsoleSingleton class for more details.
521
522 @see ConsoleSingleton
523 */
524 enum class IntendedRecipient
525 {
526 All, // All recipients, Developers and Users (One notification covers all)
527 User, // User only (notification intended only for a user)
528 Developer, // Developer only (notification intended only for a developer)
529 };
530
531 /** Used to indicate the translation state of a message (warning, error, ...).
532 While it is possible to create a custom message via Console().Send, console provides convenience
533 functions for most common combinations.
534
535 See documentation of ConsoleSingleton class for more details.
536
537 @see ConsoleSingleton
538 */
539 enum class ContentType
540 {
541 Untranslated, // Not translated, but translatable
542 Translated, // Already translated
543 Untranslatable, // Cannot and should not be translated (Dynamic content, trace,...)
544 };
545
546 /** The Logger Interface
547 * This class describes an Interface for logging within FreeCAD. If you want to add a new
548 * "sink" to FreeCAD's logging mechanism, then inherit this class. You'll also need to
549 * register your derived class with ConsoleSingleton.
550 *
551 * @see ConsoleSingleton
552 */
553 class BaseExport ILogger
554 {
555 public:
556 ILogger() = default;
557 ILogger(const ILogger&) = delete;
558 ILogger(ILogger&&) = delete;
559 ILogger& operator=(const ILogger&) = delete;
560 ILogger& operator=(ILogger&&) = delete;
561 virtual ~ILogger() = 0;
562
563 /** Used to send a Log message at the given level.
564 * @param notifiername A string identifying the entity generating the notification.
565 * It may be the Label of the App::Document or the full label of the App::DocumentObject.
566 * @param msg The message to be notified.
567 * @param level A valid level (Log, Message, Error, Notification, CriticalNotification, ...)
568 * @param recipient A valid intended recipient (All, Developer, User).
569 * Observers may decide to process only notifications when a certain recipient is intended.
570 * @param content A valid content property (Untranslated, Translatable, Untranslatable).
571 * Observers may decide not to process notifications if they are not translated or cannot be
572 * translated (are untranslatable). Or conversely, may decide not to process already translated
573 * notifications. It is up to the intended behaviour of the observer.
574 */
575 virtual void sendLog(
576 const std::string& notifiername,
577 const std::string& msg,
578 LogStyle level,
579 IntendedRecipient recipient,
580 ContentType content
581 ) = 0;
582
583 /**
584 * Returns whether a LogStyle category is active or not
585 */
586 bool isActive(const LogStyle category) const
587 {
588 switch (category) {
589 case LogStyle::Log:
590 return bLog;
591 case LogStyle::Warning:
592 return bWrn;
593 case LogStyle::Error:
594 return bErr;
595 case LogStyle::Message:
596 return bMsg;
597 case LogStyle::Critical:
598 return bCritical;
599 case LogStyle::Notification:
600 return bNotification;
601 }
602
603 return false;
604 }
605
606 virtual const char* name()
607 {
608 return nullptr;
609 }
610 bool bErr {true};
611 bool bMsg {true};
612 bool bLog {true};
613 bool bWrn {true};
614 bool bCritical {true};
615 bool bNotification {false};
616 };
617
618
619 /** The console class
620 * This class manage all the stdio stuff. This includes
621 * Messages, Warnings, Log entries, Errors, Criticals, Notifications. The incoming Messages are
622 * distributed with the FCConsoleObserver. The FCConsole class itself makes no IO, it's more like
623 * a manager.
624 * \par
625 * ConsoleSingleton is a singleton! That means you can access the only
626 * instance of the class from every where in c++ by simply using:
627 * \code
628 * #include <Base/Console.h>
629 * Base::Console().log("Stage: %d",i);
630 * \endcode
631 * \par
632 * ConsoleSingleton is able to switch between several modes to, e.g. switch
633 * the logging on or off, or treat Warnings as Errors, and so on...
634 * @see ConsoleObserver
635 *
636 * When sending error, warnings and notifications, preferably a notifier string should be provided,
637 * this enables the observer to identify the source. Any string is possible. It is common to use
638 * the DocumentObject::getFullLabel() or the label of the Document, when available.
639 * When using the Notification Framework of the Gui (Gui/Notifications.h) and a DocumentObject is
640 * passed as notifier, getFullLabel() is used. See example below.
641 *
642 * It is important for the different observers to know whether an error/warning message is intended
643 * for a user, for a developer, or for both. This enables observers to provide distinctive
644 * behaviour. Similarly, different observers may treat differently messages if they carry
645 * translated, untranslated, or untranslatable messages.
646 *
647 * While it is possible to create a tailored message, ConsoleSingleton provides convenience
648 * functions for most common messages. A custom message can be created as follows:
649 * \code
650 * Send<Base::LogStyle::Error,
651 * Base::IntendedRecipient::Developer,
652 * Base::ContentType::Untranslatable>("OCCT", e.what());
653 * \endcode
654 *
655 * That code is equivalent to:
656 * \code
657 * DeveloperError("OCCT", e.what());
658 * \endcode
659 *
660 * These convenience functions cover most common cases:
661 * - Unqualified convenience functions, such as error() and warning(), produce messages intended to
662 * both User and Developer with an untranslated message.
663 * - Functions qualified with Developer, such as DeveloperError are intended for a Developer and
664 * are untranslatable. Functions qualified with User, such as userError are intended only for the
665 * User and a untranslated (leaving the responsibility to the observer to find the translation).
666 * - Functions qualified with Translated, such as TranslatedError, are intended for the User and
667 * the message is already translated.
668 *
669 * An observer receiving an Untranslatable or Translated message should not attempt to translate
670 * it.
671 *
672 * However, an observer receiving a Translatable message may or may not attempt to translate
673 * it, e.g. depending on whether it intends to show the message to a Log or on the UI.
674 *
675 * Observers shall use the QT translation context "Notifications" to attempt to translate an
676 * Untranslated message, if they need the localized version. Users shall mark Untranslated messages
677 * for translation.
678 *
679 * Untranslated messages have the inherent advantage that can be processed in English by observers
680 * needing the English version, while enabling other observers to retrieve a translated version.
681 *
682 * However, untranslated messages have the limitation that need to be known to the QT framework, so
683 * in practice, they need be static strings (as opposed to dynamically generated ones).
684 *
685 * Example:
686 * \code
687 * Base::Console().userError(this->getFullName(), QT_TRANSLATE_NOOP("Notifications",
688 * "Impossible to migrate Parabolas!!\n"));
689 * \endcode
690 *
691 * Currently dynamically generated strings can only be properly translated at the source. This is
692 * often the case in legacy UI code, where localized strings are already available. For these
693 * cases the solution is to indicate the translated status. For example:
694 * \code
695 * Base::Console().translatedUserError(
696 * this->getFullName(),
697 * QObject::tr("The selected edge already has a Block constraint!"));
698 * \endcode
699 *
700 * However, many of this legacy UI messages were previously a QMessageBox, and it is more
701 * convenient to use the Translations Framework provided by Gui/Notifications.h, as it takes the
702 * same arguments as QMessageBox. Additionally, the Notifications Framework takes into account the
703 * user preferences to receive intrusive (pop-ups) or non-intrusive (notification
704 * area) notifications.
705 *
706 */
707 class BaseExport ConsoleSingleton
708 {
709 public:
710 // exported functions goes here +++++++++++++++++++++++++++++++++++++++
711
712 /** Sends a message of type LogStyle (Message, Warning, Error, Log, Critical or Notification).
713 This function is used by all specific convenience functions (Send(), Message(), Warning(),
714 Error(), Log(), Critical and UserNotification, without or without notifier id).
715
716 Notification can be direct or via queue.
717 */
718 template<LogStyle, IntendedRecipient = IntendedRecipient::All, ContentType = ContentType::Untranslated, typename... Args>
719 void send(const std::string& notifiername, const char* pMsg, Args&&... args);
720
721 /// Prints a Message
722 template<typename... Args>
723 void message(const char* pMsg, Args&&... args);
724 /// Prints a warning Message
725 template<typename... Args>
726 void warning(const char* pMsg, Args&&... args);
727 /// Prints a error Message
728 template<typename... Args>
729 void error(const char* pMsg, Args&&... args);
730 /// Prints a log Message
731 template<typename... Args>
732 void log(const char* pMsg, Args&&... args);
733 /// Prints a Critical Message
734 template<typename... Args>
735 void critical(const char* pMsg, Args&&... args);
736 /// Sends a User Notification
737 template<typename... Args>
738 void userNotification(const char* pMsg, Args&&... args);
739 /// Sends an already translated User Notification
740 template<typename... Args>
741 void userTranslatedNotification(const char* pMsg, Args&&... args);
742
743
744 /// Prints a Message with source indication
745 template<typename... Args>
746 void message(const std::string& notifier, const char* pMsg, Args&&... args);
747 /// Prints a warning Message with source indication
748 template<typename... Args>
749 void warning(const std::string& notifier, const char* pMsg, Args&&... args);
750 template<typename... Args>
751 void developerWarning(const std::string& notifier, const char* pMsg, Args&&... args);
752 template<typename... Args>
753 void userWarning(const std::string& notifier, const char* pMsg, Args&&... args);
754 template<typename... Args>
755 void translatedUserWarning(const std::string& notifier, const char* pMsg, Args&&... args);
756 /// Prints a error Message with source indication
757 template<typename... Args>
758 void error(const std::string& notifier, const char* pMsg, Args&&... args);
759 template<typename... Args>
760 void developerError(const std::string& notifier, const char* pMsg, Args&&... args);
761 template<typename... Args>
762 /// A noexcept DeveloperError for use in destructors. When compiled in debug, terminates via an
763 /// assert. In release, the exception is silently caught and dropped.
764 void destructorError(const std::string& notifier, const char* pMsg, Args&&... args) noexcept;
765 template<typename... Args>
766 void userError(const std::string& notifier, const char* pMsg, Args&&... args);
767 template<typename... Args>
768 void translatedUserError(const std::string& notifier, const char* pMsg, Args&&... args);
769 /// Prints a log Message with source indication
770 template<typename... Args>
771 void log(const std::string& notifier, const char* pMsg, Args&&... args);
772 /// Prints a Critical Message with source indication
773 template<typename... Args>
774 void critical(const std::string& notifier, const char* pMsg, Args&&... args);
775 /// Sends a User Notification with source indication
776 template<typename... Args>
777 void userNotification(const std::string& notifier, const char* pMsg, Args&&... args);
778 /// Sends an already translated User Notification with source indication
779 template<typename... Args>
780 void userTranslatedNotification(const std::string& notifier, const char* pMsg, Args&&... args);
781
782 // Notify a message directly to observers
783 template<LogStyle, IntendedRecipient = IntendedRecipient::All, ContentType = ContentType::Untranslated>
784 void notify(const std::string& notifiername, const std::string& msg);
785
786 /// Attaches an Observer to FCConsole
787 void attachObserver(ILogger* pcObserver);
788 /// Detaches an Observer from FCConsole
789 void detachObserver(ILogger* pcObserver);
790
791 /// enumeration for the console modes
792 enum ConsoleMode
793 {
794 Verbose = 1, // suppress Log messages
795 };
796 enum ConnectionMode
797 {
798 Direct = 0,
799 Queued = 1
800 };
801
802 enum FreeCAD_ConsoleMsgType
803 {
804 MsgType_Txt = 1,
805 MsgType_Log = 2, // ConsoleObserverStd sends this and higher to stderr
806 MsgType_Wrn = 4,
807 MsgType_Err = 8,
808 MsgType_Critical = 16, // Special message to notify critical information
809 MsgType_Notification = 32, // Special message to for notifications to the user
810 };
811
812 /// Enables or disables message types of a certain console observer
813 ConsoleMsgFlags setEnabledMsgType(const char* sObs, ConsoleMsgFlags type, bool on) const;
814 /// Checks if message types of a certain console observer are enabled
815 bool isMsgTypeEnabled(const char* sObs, FreeCAD_ConsoleMsgType type) const;
816 void setConnectionMode(ConnectionMode mode);
817
818 int* getLogLevel(const char* tag, bool create = true);
819
820 void setDefaultLogLevel(const int level)
821 {
822 _defaultLogLevel = level;
823 }
824
825 int logLevel(const int level) const
826 {
827 return level < 0 ? _defaultLogLevel : level;
828 }
829
830 /// singleton
831 static ConsoleSingleton& instance();
832
833 // retrieval of an observer by name
834 ILogger* get(const char* Name) const;
835
836 static PyMethodDef Methods[];
837
838 void refresh() const;
839 void enableRefresh(bool enable);
840
841 constexpr FreeCAD_ConsoleMsgType getConsoleMsg(LogStyle style);
842
843 private:
844 // python exports goes here +++++++++++++++++++++++++++++++++++++++++++
845 // static python wrapper of the exported functions
846 static PyObject* sPyLog(PyObject* self, PyObject* args);
847 static PyObject* sPyMessage(PyObject* self, PyObject* args);
848 static PyObject* sPyWarning(PyObject* self, PyObject* args);
849 static PyObject* sPyDeveloperWarning(PyObject* self, PyObject* args);
850 static PyObject* sPyUserWarning(PyObject* self, PyObject* args);
851 static PyObject* sPyTranslatedUserWarning(PyObject* self, PyObject* args);
852 static PyObject* sPyError(PyObject* self, PyObject* args);
853 static PyObject* sPyDeveloperError(PyObject* self, PyObject* args);
854 static PyObject* sPyUserError(PyObject* self, PyObject* args);
855 static PyObject* sPyTranslatedUserError(PyObject* self, PyObject* args);
856 static PyObject* sPyCritical(PyObject* self, PyObject* args);
857 static PyObject* sPyNotification(PyObject* self, PyObject* args);
858 static PyObject* sPyTranslatedNotification(PyObject* self, PyObject* args);
859 static PyObject* sPySetStatus(PyObject* self, PyObject* args);
860 static PyObject* sPyGetStatus(PyObject* self, PyObject* args);
861 static PyObject* sPyGetObservers(PyObject* self, PyObject* args);
862
863 bool _bCanRefresh {true};
864 ConnectionMode connectionMode {Direct};
865
866 // Singleton!
867 ConsoleSingleton();
868 ~ConsoleSingleton();
869
870 public:
871 ConsoleSingleton(const ConsoleSingleton&) = delete;
872 ConsoleSingleton(ConsoleSingleton&&) = delete;
873 ConsoleSingleton& operator=(const ConsoleSingleton&) = delete;
874 ConsoleSingleton& operator=(ConsoleSingleton&&) = delete;
875
876 private:
877 void postEvent(
878 FreeCAD_ConsoleMsgType type,
879 IntendedRecipient recipient,
880 ContentType content,
881 const std::string& notifiername,
882 const std::string& msg
883 );
884 void notifyPrivate(
885 LogStyle category,
886 IntendedRecipient recipient,
887 ContentType content,
888 const std::string& notifiername,
889 const std::string& msg
890 ) const;
891
892 // singleton
893 static void Destruct();
894 static ConsoleSingleton* _pcSingleton; // NOLINT
895
896 // observer list
897 std::set<ILogger*> _aclObservers;
898
899 std::map<std::string, int> _logLevels;
900 int _defaultLogLevel;
901
902 friend class ConsoleOutput;
903 };
904
905 /** Access to the Console
906 * This method is used to gain access to the one and only instance of
907 * the ConsoleSingleton class.
908 */
909 inline ConsoleSingleton& Console()
910 {
911 return ConsoleSingleton::instance();
912 }
913
914 constexpr ConsoleSingleton::FreeCAD_ConsoleMsgType ConsoleSingleton::getConsoleMsg(LogStyle style)
915 {
916 constexpr std::array msgTypes {
917 // In order of LogStyle
918 MsgType_Wrn,
919 MsgType_Txt,
920 MsgType_Err,
921 MsgType_Log,
922 MsgType_Critical,
923 MsgType_Notification
924 };
925
926 return msgTypes.at(static_cast<std::size_t>(style));
927 }
928
929 class BaseExport ConsoleRefreshDisabler
930 {
931 public:
932 ConsoleRefreshDisabler()
933 {
934 Console().enableRefresh(false);
935 }
936
937 ~ConsoleRefreshDisabler()
938 {
939 Console().enableRefresh(true);
940 }
941
942 ConsoleRefreshDisabler(const ConsoleRefreshDisabler&) = delete;
943 ConsoleRefreshDisabler(ConsoleRefreshDisabler&&) = delete;
944 ConsoleRefreshDisabler& operator=(const ConsoleRefreshDisabler&) = delete;
945 ConsoleRefreshDisabler& operator=(ConsoleRefreshDisabler&&) = delete;
946 };
947
948
949 /** LogLevel helper class */
950 class BaseExport LogLevel
951 {
952 public:
953 std::string tag;
954 int& lvl;
955 bool print_tag;
956 int print_src;
957 bool print_time;
958 bool add_eol;
959 bool refresh;
960
961 LogLevel(
962 const char* tag,
963 const bool print_tag = true,
964 const int print_src = 0,
965 const bool print_time = false,
966 const bool add_eol = true,
967 const bool refresh = false
968 )
969 : tag(tag)
970 , lvl(*Console().getLogLevel(tag))
971 , print_tag(print_tag)
972 , print_src(print_src)
973 , print_time(print_time)
974 , add_eol(add_eol)
975 , refresh(refresh)
976 {}
977
978 bool isEnabled(const int lev) const
979 {
980 return lev <= level();
981 }
982
983 int level() const
984 {
985 return Console().logLevel(lvl);
986 }
987
988 std::stringstream& prefix(std::stringstream& str, const char* src, int line);
989 };
990 } // namespace Base
991
992 /** Prints a Message
993 * This method issues a Message.
994 * Messages are used to show some non vital information. That means when
995 * FreeCAD is running in GUI mode a Message appears on the status bar.
996 * In console mode a message is printed to the console.
997 * \par
998 * You can use a printf like interface like:
999 * \code
1000 * Console().Message("Doing something important %d times\n",i);
1001 * \endcode
1002 * @see Warning
1003 * @see Error
1004 * @see Log
1005 * @see Critical
1006 * @see UserNotification
1007 * @see UserTranslatedNotification
1008 */
1009 template<typename... Args>
1010 void Base::ConsoleSingleton::message(const char* pMsg, Args&&... args)
1011 {
1012 message(std::string(""), pMsg, std::forward<Args>(args)...);
1013 }
1014
1015 template<typename... Args>
1016 void Base::ConsoleSingleton::message(const std::string& notifier, const char* pMsg, Args&&... args)
1017 {
1018 send<LogStyle::Message>(notifier, pMsg, std::forward<Args>(args)...);
1019 }
1020
1021 template<typename... Args>
1022 void Base::ConsoleSingleton::warning(const char* pMsg, Args&&... args)
1023 {
1024 warning(std::string(""), pMsg, std::forward<Args>(args)...);
1025 }
1026
1027 template<typename... Args>
1028 void Base::ConsoleSingleton::warning(const std::string& notifier, const char* pMsg, Args&&... args)
1029 {
1030 send<LogStyle::Warning>(notifier, pMsg, std::forward<Args>(args)...);
1031 }
1032
1033 template<typename... Args>
1034 void Base::ConsoleSingleton::developerWarning(const std::string& notifier, const char* pMsg, Args&&... args)
1035 {
1036 send<LogStyle::Warning, IntendedRecipient::Developer, ContentType::Untranslatable>(
1037 notifier,
1038 pMsg,
1039 std::forward<Args>(args)...
1040 );
1041 }
1042
1043 template<typename... Args>
1044 void Base::ConsoleSingleton::userWarning(const std::string& notifier, const char* pMsg, Args&&... args)
1045 {
1046 send<LogStyle::Warning, IntendedRecipient::User, ContentType::Untranslated>(
1047 notifier,
1048 pMsg,
1049 std::forward<Args>(args)...
1050 );
1051 }
1052
1053 template<typename... Args>
1054 void Base::ConsoleSingleton::translatedUserWarning(
1055 const std::string& notifier,
1056 const char* pMsg,
1057 Args&&... args
1058 )
1059 {
1060 send<LogStyle::Warning, IntendedRecipient::User, ContentType::Translated>(
1061 notifier,
1062 pMsg,
1063 std::forward<Args>(args)...
1064 );
1065 }
1066
1067 template<typename... Args>
1068 void Base::ConsoleSingleton::error(const char* pMsg, Args&&... args)
1069 {
1070 error(std::string(""), pMsg, std::forward<Args>(args)...);
1071 }
1072
1073 template<typename... Args>
1074 void Base::ConsoleSingleton::error(const std::string& notifier, const char* pMsg, Args&&... args)
1075 {
1076 send<LogStyle::Error>(notifier, pMsg, std::forward<Args>(args)...);
1077 }
1078
1079 template<typename... Args>
1080 void Base::ConsoleSingleton::developerError(const std::string& notifier, const char* pMsg, Args&&... args)
1081 {
1082 send<LogStyle::Error, IntendedRecipient::Developer, ContentType::Untranslatable>(
1083 notifier,
1084 pMsg,
1085 std::forward<Args>(args)...
1086 );
1087 }
1088
1089 template<typename... Args>
1090 void Base::ConsoleSingleton::destructorError(
1091 const std::string& notifier,
1092 const char* pMsg,
1093 Args&&... args
1094 ) noexcept
1095 {
1096 try {
1097 send<LogStyle::Error, IntendedRecipient::Developer, ContentType::Untranslatable>(
1098 notifier,
1099 pMsg,
1100 std::forward<Args>(args)...
1101 );
1102 }
1103 catch (...) {
1104 assert("An exception was thrown while attempting console output in a destructor" && false);
1105 }
1106 }
1107
1108 template<typename... Args>
1109 void Base::ConsoleSingleton::userError(const std::string& notifier, const char* pMsg, Args&&... args)
1110 {
1111 send<LogStyle::Error, IntendedRecipient::User, ContentType::Untranslated>(
1112 notifier,
1113 pMsg,
1114 std::forward<Args>(args)...
1115 );
1116 }
1117
1118 template<typename... Args>
1119 void Base::ConsoleSingleton::translatedUserError(
1120 const std::string& notifier,
1121 const char* pMsg,
1122 Args&&... args
1123 )
1124 {
1125 send<LogStyle::Error, IntendedRecipient::User, ContentType::Translated>(
1126 notifier,
1127 pMsg,
1128 std::forward<Args>(args)...
1129 );
1130 }
1131
1132 template<typename... Args>
1133 void Base::ConsoleSingleton::critical(const char* pMsg, Args&&... args)
1134 {
1135 critical(std::string(""), pMsg, std::forward<Args>(args)...);
1136 }
1137
1138 template<typename... Args>
1139 void Base::ConsoleSingleton::critical(const std::string& notifier, const char* pMsg, Args&&... args)
1140 {
1141 send<LogStyle::Critical>(notifier, pMsg, std::forward<Args>(args)...);
1142 }
1143
1144 template<typename... Args>
1145 void Base::ConsoleSingleton::userNotification(const char* pMsg, Args&&... args)
1146 {
1147 userNotification(std::string(""), pMsg, std::forward<Args>(args)...);
1148 }
1149
1150 template<typename... Args>
1151 void Base::ConsoleSingleton::userNotification(const std::string& notifier, const char* pMsg, Args&&... args)
1152 {
1153 send<LogStyle::Notification, IntendedRecipient::User, ContentType::Untranslated>(
1154 notifier,
1155 pMsg,
1156 std::forward<Args>(args)...
1157 );
1158 }
1159
1160 template<typename... Args>
1161 void Base::ConsoleSingleton::userTranslatedNotification(const char* pMsg, Args&&... args)
1162 {
1163 userTranslatedNotification(std::string(""), pMsg, std::forward<Args>(args)...);
1164 }
1165
1166 template<typename... Args>
1167 void Base::ConsoleSingleton::userTranslatedNotification(
1168 const std::string& notifier,
1169 const char* pMsg,
1170 Args&&... args
1171 )
1172 {
1173 send<LogStyle::Notification, IntendedRecipient::User, ContentType::Translated>(
1174 notifier,
1175 pMsg,
1176 std::forward<Args>(args)...
1177 );
1178 }
1179
1180 template<typename... Args>
1181 void Base::ConsoleSingleton::log(const char* pMsg, Args&&... args)
1182 {
1183 log(std::string(""), pMsg, std::forward<Args>(args)...);
1184 }
1185
1186 template<typename... Args>
1187 void Base::ConsoleSingleton::log(const std::string& notifier, const char* pMsg, Args&&... args)
1188 {
1189 send<LogStyle::Log>(notifier, pMsg, std::forward<Args>(args)...);
1190 }
1191
1192 template<
1193 Base::LogStyle category,
1194 Base::IntendedRecipient recipient /*= Base::IntendedRecipient::All*/,
1195 Base::ContentType contenttype /*= Base::ContentType::Untranslated*/,
1196 typename... Args>
1197 void Base::ConsoleSingleton::send(const std::string& notifiername, const char* pMsg, Args&&... args)
1198 {
1199 std::string format;
1200 try {
1201 format = fmt::sprintf(pMsg, args...);
1202 }
1203 catch (fmt::format_error& e) {
1204 // We can't allow an exception to propagate out of this method, which gets used in some
1205 // destructors. Instead, make the string's contents the error message that fmt::sprintf gave
1206 // us.
1207 format = std::string("ERROR: Invalid format string or arguments provided.\n");
1208 format += e.what();
1209 }
1210
1211 if (connectionMode == Direct) {
1212 notify<category, recipient, contenttype>(notifiername, format);
1213 }
1214 else {
1215
1216 const auto type = getConsoleMsg(category);
1217
1218 postEvent(type, recipient, contenttype, notifiername, format);
1219 }
1220 }
1221
1222 template<
1223 Base::LogStyle category,
1224 Base::IntendedRecipient recipient /*= Base::IntendedRecipient::All*/,
1225 Base::ContentType contenttype /*= Base::ContentType::Untranslated*/>
1226 void Base::ConsoleSingleton::notify(const std::string& notifiername, const std::string& msg)
1227 {
1228 notifyPrivate(category, recipient, contenttype, notifiername, msg);
1229 }
1230
1231 #if defined(__clang__)
1232 # pragma clang diagnostic pop
1233 #endif
1234
1235 #endif // BASE_CONSOLE_H