Debian Codegraph @

include/deal.II/base/logstream.h

raw
1 // ------------------------------------------------------------------------
2 //
3 // SPDX-License-Identifier: LGPL-2.1-or-later
4 // Copyright (C) 1998 - 2024 by the deal.II authors
5 //
6 // This file is part of the deal.II library.
7 //
8 // Part of the source code is dual licensed under Apache-2.0 WITH
9 // LLVM-exception OR LGPL-2.1-or-later. Detailed license information
10 // governing the source code and code contributions can be found in
11 // LICENSE.md and CONTRIBUTING.md at the top level directory of deal.II.
12 //
13 // ------------------------------------------------------------------------
14
15 #ifndef dealii_logstream_h
16 #define dealii_logstream_h
17
18 #include <deal.II/base/config.h>
19
20 #include <deal.II/base/enable_observer_pointer.h>
21 #include <deal.II/base/exceptions.h>
22 #include <deal.II/base/observer_pointer.h>
23 #include <deal.II/base/thread_local_storage.h>
24
25 #include <cmath>
26 #include <memory>
27 #include <sstream>
28 #include <stack>
29 #include <string>
30
31
32 DEAL_II_NAMESPACE_OPEN
33
34 /**
35 * A class that simplifies the process of execution logging. It does so by
36 * providing
37 * <ul>
38 * <li> a push and pop mechanism for prefixes, and
39 * <li> the possibility of distributing information to files and the console.
40 * </ul>
41 *
42 * The usual usage of this class is through the pregenerated object
43 * <tt>deallog</tt>. Typical setup steps are:
44 * <ul>
45 * <li> <tt>deallog.depth_console(n)</tt>: restrict output on screen to outer
46 * loops.
47 * <li> <tt>deallog.attach(std::ostream)</tt>: write logging information into
48 * a file.
49 * <li> <tt>deallog.depth_file(n)</tt>: restrict output to file to outer
50 * loops.
51 * </ul>
52 *
53 * Before entering a new phase of your program, e.g. a new loop, a new prefix
54 * can be set via <tt>LogStream::Prefix p("loopname");</tt>. The destructor of
55 * the prefix will pop the prefix text from the stack.
56 *
57 * Write via the <tt>&lt;&lt;</tt> operator, <tt> deallog << "This is a log
58 * notice";</tt> will be buffered thread locally until a <tt>std::flush</tt>
59 * or <tt>std::endl</tt> is encountered, which will trigger a writeout to the
60 * console and, if set up, the log file.
61 *
62 * <h3>LogStream and thread safety</h3>
63 *
64 * In the vicinity of concurrent threads, LogStream behaves in the following
65 * manner:
66 * <ul>
67 * <li> Every write to a Logstream with operator <tt>&lt;&lt;</tt> (or with
68 * one of the special member functions) is buffered in a thread-local storage.
69 * <li> An <tt>std::flush</tt> or <tt>std::endl</tt> will trigger a writeout
70 * to the console and (if attached) to the file stream. This writeout is
71 * sequentialized so that output from concurrent threads don't interleave.
72 * <li> On a new thread, invoking a writeout, as well as a call to #push or
73 * #pop will copy the current prefix of the "blessed" thread that created the
74 * LogStream instance to a thread-local storage. After that prefixes are
75 * thread-local.
76 * </ul>
77 *
78 * @ingroup textoutput
79 */
80 class LogStream : public EnableObserverPointer
81 {
82 public:
83 /**
84 * A subclass allowing for the safe generation and removal of prefixes.
85 *
86 * Somewhere at the beginning of a block, create one of these objects, and
87 * it will appear as a prefix in LogStream output like @p deallog. At the
88 * end of the block, the prefix will automatically be removed, when this
89 * object is destroyed.
90 *
91 * In other words, the scope of the object so created determines the
92 * lifetime of the prefix. The advantage of using such an object is that the
93 * prefix is removed whichever way you exit the scope -- by
94 * <code>continue</code>, <code>break</code>, <code>return</code>,
95 * <code>throw</code>, or by simply reaching the closing brace. In all of
96 * these cases, it is not necessary to remember to pop the prefix manually
97 * using LogStream::pop(). In this, it works just like the better known
98 * std::unique_ptr and std::lock_guard classes.
99 */
100 class Prefix
101 {
102 public:
103 /**
104 * Set a new prefix for @p deallog, which will be removed when the
105 * variable is destroyed.
106 */
107 Prefix(const std::string &text);
108
109 /**
110 * Set a new prefix for the given stream, which will be removed when the
111 * variable is destroyed.
112 */
113 Prefix(const std::string &text, LogStream &stream);
114
115 /**
116 * Remove the prefix associated with this variable.
117 */
118 ~Prefix();
119
120 private:
121 /**
122 * A pointer to the LogStream object to which the prefix is
123 * applied.
124 */
125 ObserverPointer<LogStream, LogStream::Prefix> stream;
126 };
127
128
129 /**
130 * Standard constructor. The constructor sets the output stream to
131 * <tt>std::cout</tt> and the depth to zero. (Use attach() and
132 * depth_console() to change this.)
133 */
134 LogStream();
135
136
137 /**
138 * Destructor.
139 */
140 ~LogStream() override;
141
142
143 /**
144 * Enable output to a second stream <tt>o</tt>.
145 *
146 * @param o Attach this output stream.
147 *
148 * @param[in] print_job_id Whether or not the JobIdentifier for the current
149 * process should be printed to the stream.
150 *
151 * @param[in] flags Format flags to set on the output stream @p o.
152 */
153 void
154 attach(std::ostream &o,
155 const bool print_job_id = true,
156 const std::ios_base::fmtflags flags = std::ios::showpoint |
157 std::ios::left);
158
159
160 /**
161 * Disable output to the second stream. You may want to call <tt>close</tt>
162 * on the stream that was previously attached to this object.
163 */
164 void
165 detach();
166
167
168 /**
169 * Return the default stream (<tt>std_out</tt>).
170 */
171 std::ostream &
172 get_console();
173
174
175 /**
176 * Return the file stream.
177 */
178 std::ostream &
179 get_file_stream();
180
181
182 /**
183 * Return @p true if file stream has already been attached,
184 * @p false otherwise.
185 */
186 bool
187 has_file() const;
188
189
190 /**
191 * Return the prefix string.
192 */
193 const std::string &
194 get_prefix() const;
195
196
197 /**
198 * Push another prefix on the stack. Prefixes are automatically separated by
199 * a colon and there is a double colon after the last prefix.
200 *
201 * A simpler way to add a prefix (without the manual need to add the
202 * corresponding pop()) is to use the LogStream::Prefix class. Using
203 * that class has the advantage that the corresponding pop() call is
204 * issued whenever the Prefix object goes out of scope -- either at
205 * the end of the code block, at the nearest @p return statement, or
206 * because an intermediate function call results in an exception that
207 * is not immediately caught.
208 */
209 void
210 push(const std::string &text);
211
212
213 /**
214 * Remove the last prefix added with push().
215 */
216 void
217 pop();
218
219
220 /**
221 * Set the maximum number of levels to be printed on the console. The default
222 * is 0, which will not generate any output. This function allows one to
223 * restrict console output to the highest levels of iterations. Only output
224 * with less than <tt>n</tt> prefixes is printed. By calling this function
225 * with <tt>n=0</tt>, no console output will be written. See step-3 for an
226 * example usage of this method.
227 *
228 * The previous value of this parameter is returned.
229 */
230 unsigned int
231 depth_console(const unsigned int n);
232
233
234 /**
235 * Set the maximum number of levels to be written to the log file. The
236 * functionality is the same as <tt>depth_console</tt>, nevertheless, this
237 * function should be used with care, since it may spoil the value of a log
238 * file.
239 *
240 * The previous value of this parameter is returned.
241 */
242 unsigned int
243 depth_file(const unsigned int n);
244
245
246 /**
247 * Log the thread id.
248 */
249 bool
250 log_thread_id(const bool flag);
251
252
253 /**
254 * Set the precision for the underlying stream and returns the previous
255 * stream precision. This function mimics
256 * http://www.cplusplus.com/reference/ios/ios_base/precision/
257 */
258 std::streamsize
259 precision(const std::streamsize prec);
260
261
262 /**
263 * Set the width for the underlying stream and returns the previous stream
264 * width. This function mimics
265 * http://www.cplusplus.com/reference/ios/ios_base/width/
266 */
267 std::streamsize
268 width(const std::streamsize wide);
269
270
271 /**
272 * set the flags for the underlying stream and returns the previous stream
273 * flags. This function mimics
274 * http://www.cplusplus.com/reference/ios/ios_base/flags/
275 */
276 std::ios::fmtflags
277 flags(const std::ios::fmtflags f);
278
279
280 /**
281 * Treat ostream manipulators. This passes on the whole thing to the
282 * template function with the exception of the <tt>std::endl</tt>
283 * manipulator, for which special action is performed: write the temporary
284 * stream buffer including a header to the file and <tt>std::cout</tt> and
285 * empty the buffer.
286 *
287 * An overload of this function is needed anyway, since the compiler can't
288 * bind manipulators like @p std::endl directly to template arguments @p T
289 * like in the previous general template. This is due to the fact that @p
290 * std::endl is actually an overloaded set of functions for @p std::ostream,
291 * @p std::wostream, and potentially more of this kind. This function is
292 * therefore necessary to pick one element from this overload set.
293 */
294 LogStream &
295 operator<<(std::ostream &(*p)(std::ostream &));
296
297
298 /**
299 * Return an estimate for the memory consumption, in bytes, of this object.
300 * This is not exact (but will usually be close) because calculating the
301 * memory usage of trees (e.g., <tt>std::map</tt>) is difficult.
302 */
303 std::size_t
304 memory_consumption() const;
305
306 private:
307 /**
308 * Internal wrapper around thread-local prefixes. This private function will
309 * return the correct internal prefix stack. More important, a new
310 * thread-local stack will be copied from the current stack of the "blessed"
311 * thread that created this LogStream instance (usually, in the case of
312 * deallog, the "main" thread).
313 */
314 std::stack<std::string> &
315 get_prefixes() const;
316
317 /**
318 * Stack of strings which are printed at the beginning of each line to allow
319 * identification where the output was generated.
320 */
321 mutable Threads::ThreadLocalStorage<std::stack<std::string>> prefixes;
322
323 /**
324 * We record the thread id of the thread creating this object. We need
325 * this information to "steal" the current prefix from this "parent"
326 * thread on first use of deallog on a new thread.
327 */
328 std::thread::id parent_thread;
329
330 /**
331 * Default stream, where the output is to go to. This stream defaults to
332 * <tt>std::cout</tt>, but can be set to another stream through the
333 * constructor.
334 */
335 std::ostream *std_out;
336
337 /**
338 * Pointer to a stream, where a copy of the output is to go to. Usually,
339 * this will be a file stream.
340 *
341 * You can set and reset this stream by the <tt>attach</tt> function.
342 */
343 std::ostream *file;
344
345 /**
346 * Value denoting the number of prefixes to be printed to the standard
347 * output. If more than this number of prefixes is pushed to the stack, then
348 * no output will be generated until the number of prefixes shrinks back
349 * below this number.
350 */
351 unsigned int std_depth;
352
353 /**
354 * Same for the maximum depth of prefixes for output to a file.
355 */
356 unsigned int file_depth;
357
358 /**
359 * Flag for printing thread id.
360 */
361 bool print_thread_id;
362
363 /**
364 * A flag indicating whether output is currently at a new line
365 */
366 bool at_newline;
367
368 /**
369 * Print head of line.
370 */
371 void
372 print_line_head();
373
374 /**
375 * Internal wrapper around "thread local" outstreams. This private function
376 * will return the correct internal ostringstream buffer for operator<<.
377 */
378 std::ostringstream &
379 get_stream();
380
381 /**
382 * We use our thread local storage facility to generate a stringstream for
383 * every thread that sends log messages.
384 */
385 Threads::ThreadLocalStorage<std::shared_ptr<std::ostringstream>> outstreams;
386
387 template <typename T>
388 friend LogStream &
389 operator<<(LogStream &log, const T &t);
390 };
391
392
393 /* ----------------------------- Inline functions and templates ----------------
394 */
395
396
397 /**
398 * Output a constant something through LogStream:
399 *
400 * @note We declare this operator as a non-member function so that it is
401 * possible to overload it with more specialized templated versions under
402 * C++11 overload resolution rules
403 */
404 template <typename T>
405 inline LogStream &
406 operator<<(LogStream &log, const T &t)
407 {
408 // print to the internal stringstream
409 log.get_stream() << t;
410 return log;
411 }
412
413
414
415 /**
416 * The standard log object of deal.II. Take a look at the documentation of
417 * the LogStream class for more information, as well as below.
418 *
419 * The @p deallog
420 * variable (which stands for deal-log, not de-allog) represents a
421 * stream to which some parts of the library write output. For
422 * example, iterative solvers will generate diagnostics (starting
423 * residual, number of solver steps, final residual).
424 *
425 * The output of @p deallog can be written to the console, to a file,
426 * or both. Both are disabled by default since over the years we have
427 * learned that a program should only generate output when a user
428 * explicitly asks for it. But this can be changed, and to explain how
429 * this can be done, we need to explain how @p deallog works: When
430 * individual parts of the library want to log output, they open a
431 * "context" or "section" into which this output will be placed. At
432 * the end of the part that wants to write output, one exits this
433 * section again. Since a function may call another one from within
434 * the scope where this output section is open, output may in fact be
435 * nested hierarchically into these sections. The LogStream class of
436 * which @p deallog is a variable calls each of these sections a
437 * "prefix" because all output is printed with this prefix at the left
438 * end of the line, with prefixes separated by colons. There is always
439 * a default prefix called "DEAL" (a hint at deal.II's history as the
440 * successor of a previous library called "DEAL" and from which the
441 * LogStream class is one of the few pieces of code that were taken
442 * into deal.II).
443 *
444 * By default, @p logstream only outputs lines with zero prefixes --
445 * i.e., all output is disabled because the default "DEAL" prefix is
446 * always there. But one can set a different maximal number of
447 * prefixes for lines that should be output to something larger,
448 * by calling LogStream::depth_console() with an integer argument. Let's
449 * assume you call it with `2` as argument. This means that for all screen
450 * output a context that has pushed one additional prefix beyond the default
451 * "DEAL" is allowed to print its output to the screen ("console"),
452 * whereas all further nested sections that would have three or more
453 * prefixes active would write to @p deallog, but @p deallog does not
454 * forward this output to the screen.
455 */
456 extern LogStream deallog;
457
458
459
460 DEAL_II_NAMESPACE_CLOSE
461
462 #endif