Loading...
Searching...
No Matches
logging.hpp
Go to the documentation of this file.
1
2
3#pragma once
4
5#include <iomanip>
6#include <iostream>
7#include <utility>
8
9#include "mpi/mpi.hpp"
10#include "timestamp.hpp"
11
12namespace terra::util {
13
14namespace detail {
15
16/// @brief std::ostream subclass to enable logging with prefix and only on root.
17///
18/// Use global instances of this class like `logroot` as a replacement for std::cout.
19class PrefixCout final : std::streambuf, public std::ostream
20{
21 std::function< std::string() > prefix_;
22 bool only_root_;
23 bool at_line_start_ = true;
24
25 public:
26 explicit PrefixCout(
27 std::function< std::string() > prefix = []() { return ""; },
28 bool only_root = true )
29 : std::ostream( this )
30 , prefix_( std::move( prefix ) )
31 , only_root_( only_root )
32 {}
33
34 int overflow( int ch ) override
35 {
36 if ( only_root_ && mpi::rank() != 0 )
37 {
38 return 0;
39 }
40
41 if ( ch == EOF )
42 {
43 return EOF;
44 }
45
46 if ( at_line_start_ )
47 {
48 std::cout << prefix_();
49 at_line_start_ = false;
50 }
51
52 std::cout.put( static_cast< char >( ch ) );
53
54 if ( ch == '\n' )
55 {
56 std::cout.flush();
57 at_line_start_ = true;
58 }
59
60 return ch;
61 }
62};
63
64inline std::string log_prefix()
65{
66 std::stringstream ss;
67 ss << "[LOG | rank " << std::setw( static_cast< int >( std::to_string( mpi::num_processes() - 1 ).size() ) )
68 << mpi::rank() << " | " << current_timestamp() + "] ";
69 return ss.str();
70}
71
72} // namespace detail
73
74/// @brief std::ostream subclass that just logs on root and adds a timestamp for each line.
75///
76/// You should be able to use this as a plugin replacement for std::cout.
77inline detail::PrefixCout logroot( []() { return detail::log_prefix(); } );
78
79/// @brief std::ostream subclass that just logs on any process and adds a timestamp for each line.
80///
81/// You should be able to use this as a plugin replacement for std::cout.
82inline detail::PrefixCout logall( []() { return detail::log_prefix(); }, false );
83
84} // namespace terra::util
std::ostream subclass to enable logging with prefix and only on root.
Definition logging.hpp:20
int overflow(int ch) override
Definition logging.hpp:34
PrefixCout(std::function< std::string() > prefix=[]() { return "";}, bool only_root=true)
Definition logging.hpp:26
int num_processes()
Definition mpi.hpp:17
MPIRank rank()
Definition mpi.hpp:10
std::string log_prefix()
Definition logging.hpp:64
Definition solver.hpp:9
detail::PrefixCout logall([]() { return detail::log_prefix();}, false)
std::ostream subclass that just logs on any process and adds a timestamp for each line.
std::string current_timestamp()
Get the current timestamp as a string.
Definition timestamp.hpp:10
detail::PrefixCout logroot([]() { return detail::log_prefix();})
std::ostream subclass that just logs on root and adds a timestamp for each line.