Flow123d  JS_before_hm-978-gfd4e3d8
logger.hh
Go to the documentation of this file.
1 /*!
2  *
3  * Copyright (C) 2015 Technical University of Liberec. All rights reserved.
4  *
5  * This program is free software; you can redistribute it and/or modify it under
6  * the terms of the GNU General Public License version 3 as published by the
7  * Free Software Foundation. (http://www.gnu.org/licenses/gpl-3.0.en.html)
8  *
9  * This program is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
12  *
13  *
14  * @file logger.hh
15  * @brief
16  */
17 
18 #ifndef LOGGER_HH_
19 #define LOGGER_HH_
20 
21 
22 #include <iostream>
23 #include <algorithm> // for forward
24 #include <string> // for string
25 #include <sstream>
26 #include <vector>
27 #include <string>
28 
29 
30 #include "system/fmt/format.h"
31 #include "system/exc_common.hh"
32 
33 
34 
35 /**
36  * @brief Helper class, store mask specifying streams
37  *
38  * Defines masks of all used streams as static methods and allows combining and comparing masks using
39  * the overloaded operators.
40  */
41 class StreamMask {
42 public:
43  /// Empty constructor
45  : mask_(0) {}
46 
47  /// Constructor set \p mask_ value
48  StreamMask(int mask)
49  : mask_(mask) {}
50 
51  /// Predefined mask of std::cout output
52  static StreamMask cout;
53 
54  /// Predefined mask of std::cerr output
55  static StreamMask cerr;
56 
57  /// Predefined mask of log file output
58  static StreamMask log;
59 
60  // Overload & operator
61  StreamMask operator &(const StreamMask &other);
62 
63  // Overload | operator
64  StreamMask operator |(const StreamMask &other);
65 
66  // Overload () operator
67  int operator()(void);
68 
69 private:
70  int mask_;
71 };
72 
73 
74 /**
75  * @brief Class for storing logger messages.
76  *
77  * Allow define different levels of log messages and distinguish output streams
78  * for individual leves. These output streams are -
79  * - standard console output (std::cout)
80  * - standard error output (std::cerr)
81  * - file output (see \p LoggerOptions class)
82  *
83  * Logger distinguishes four type of levels -
84  * - warning: printed to standard error and file output
85  * - message: printed to standard console and file output
86  * - log: printed to file output
87  * - debug: printed to file output (level is used only in debug mode)
88  *
89  * File output is optional. See \p LoggerOptions for setting this output stream.
90  *
91  * <b>Example of Logger usage:</b>
92  *
93  * For individual levels are defined macros -
94  * - MessageOut()
95  * - WarningOut()
96  * - LogOut()
97  * - DebugOut()
98  * that ensure display of actual code point (source file, line and function).
99  *
100  * Logger message is created by using an operator << and allow to add each type
101  * that has override this operator. Message is terminated with manipulator
102  * std::endl. Implicitly logger message is printed only in processor with rank
103  * zero. If necessary printed message for all process, it provides a method
104  * every_proc().
105  *
106  * Examples of logger messages formating:
107  *
108  @code
109  MessageOut() << "End of simulation at time: " << secondary_eq->solved_time() << "\n";
110  WarningOut() << "Unprocessed keys '" << keys_vec << "'." << "\n";
111  LogOut() << "Write output to output stream: " << this->_base_filename << " for time: " << time << "\n";
112  DebugOut() << "Calling 'initialize' of empty equation '" << typeid(*this).name() << "'." << "\n";
113  @endcode
114  *
115  * See that output of vectors of printable objects is supported.
116  * Implementation of Logger does not support manipulator std::endl. Please, use "\n" instead.
117  * New line character "\n" can be used multiple times.
118  *
119  * Logger allow using fmtlib functionality for simpler formatting of message:
120  *
121  @code
122  MessageOut() << fmt::format("Start time: {}\nEnd time: {}\n", this->start_time(), this->end_time());
123  MessageOut().fmt("Start time: {}\nEnd time: {}\n", this->start_time(), this->end_time());
124  @endcode
125  *
126  * Messages are printed only on the zero MPI process by default.
127  * Parallel output on all processes must be required explicitly:
128  *
129  @code
130  MessageOut().every_proc() << "Size distributed at process: " << distr->lsize() << "\n";
131  @endcode
132  *
133  *
134  */
135 class Logger : public std::ostream {
136 public:
137  /// Enum of types of Logger messages.
138  enum MsgType {
139  warning = 0,
140  message = 1,
141  log = 2,
142  debug = 3,
143  error = 4
144  };
145 
146  /// Return string value of given MsgType in full or shorter format (e.g. "WARNING" of "Wrn")
147  static const std::string msg_type_string(MsgType msg_type, bool full_format = true);
148 
149  /// Constructor.
150  Logger(MsgType type);
151 
152  /// Stores values for printing out line number, function, etc
153  Logger& set_context(const char* file_name, const char* function, const int line);
154 
155  /// Set flag every_process_ to true
156  Logger& every_proc();
157 
158  /**
159  * @brief Allow use functionality of fmtlib for formating message.
160  *
161  * See examples in description of Logger class.
162  */
163  template<class... T>
164  Logger& fmt(T&&... t)
165  {
166  try {
167  return *this << fmt::format(std::forward<T>(t)...);
168  } catch (const fmt::FormatError & e) {
169  THROW(ExcMessage() << EI_Message("FormatError: " + std::string(e.what())));
170  }
171  }
172 
173  /// Destructor.
174  ~Logger();
175 
176 
177 private:
178  /// Set @p streams_mask_ according to the type of message.
179  void set_mask();
180 
181  /// Print formated message to given screen stream if mask corresponds with @p streams_mask_.
182  void print_to_screen(std::ostream& stream, std::stringstream& scr_stream, StreamMask mask);
183 
184  /// Print formated message to given file stream if mask corresponds with @p streams_mask_.
185  void print_to_file(std::ofstream& stream, std::stringstream& file_stream, StreamMask mask);
186 
187  /// Print header to screen stream, helper method called from \p print_to_screen.
188  bool print_screen_header(std::stringstream& scr_stream);
189 
190  /// Print header to file stream, helper method called from \p print_to_file.
191  void print_file_header(std::stringstream& file_stream);
192 
193  /// Return compact (relative) path to the given source file.
194  std::string compact_file_name(std::string file_name);
195 
196  std::stringstream cout_stream_; ///< Store messages printed to cout output stream
197  std::stringstream cerr_stream_; ///< Store messages printed to cerr output stream
198  std::stringstream file_stream_; ///< Store messages printed to file
199 
200  MsgType type_; ///< Type of message.
201  bool every_process_; ///< Flag marked if log message is printing for all processes or only for zero process.
202  std::string file_name_; ///< Actual file.
203  std::string function_; ///< Actual function.
204  int line_; ///< Actual line.
205  std::string date_time_; ///< Actual date and time.
206  int mpi_rank_; ///< Actual process (if MPI is supported)
207  StreamMask streams_mask_; ///< Mask of logger, specifies streams in actual time into which to be written
208  StreamMask full_streams_mask_; ///< Mask of logger, specifies all streams into which to be written in logger message
209 
210  // Generic printing.
211  template <class T>
212  friend Logger &operator<<(Logger & log, const T & x);
213  // Vector printing support.
214  template <class T>
215  friend Logger &operator<<(Logger & log, const std::vector<T> & vec);
216  // Parametric stream modificator (.
217  friend Logger &operator<<(Logger & log, std::ostream & (*pf) (std::ostream &) );
218  // Stream mask modificator.
219  friend Logger &operator<<(Logger & log, StreamMask mask);
220 };
221 
222 
223 Logger &operator<<(Logger & log, StreamMask mask);
224 
225 
226 Logger &operator<<(Logger & log, std::ostream & (*pf) (std::ostream &) );
227 
228 
229 template <class T>
230 Logger &operator<<(Logger & log, const std::vector<T> & vec)
231 {
232  for (T const& c : vec)
233  log << c << " ";
234  return log;
235 }
236 
237 
238 template <class T>
239 Logger &operator<<(Logger & log, const T & x)
240 {
241  if ( (log.streams_mask_ & StreamMask::cout)() ) log.cout_stream_ << x;
242  if ( (log.streams_mask_ & StreamMask::cerr)() ) log.cerr_stream_ << x;
243  if ( (log.streams_mask_ & StreamMask::log )() ) log.file_stream_ << x;
244  return log;
245 }
246 
247 
248 
249 
250 
251 /// Internal macro defining universal record of log
252 #define _LOG(type) \
253  Logger( type ).set_context( __FILE__, __func__, __LINE__)
254 /// Macro defining 'message' record of log
255 #define MessageOut() \
256  _LOG( Logger::MsgType::message )
257 /// Macro defining 'warning' record of log
258 #define WarningOut() \
259  _LOG( Logger::MsgType::warning )
260 /// Macro defining 'log' record of log
261 #define LogOut() \
262  _LOG( Logger::MsgType::log )
263 /// Macro defining 'debug' record of log
264 #define DebugOut() \
265  _LOG( Logger::MsgType::debug )
266 
267 /**
268  * Print variable name and value.
269  * Usage:
270  * DebugOut() << print_var(x) << print_var(y)
271  */
272 #define print_var(var) \
273  std::string(#var) << "=" << (var) << ", "
274 
275 
276 
277 
278 #endif /* LOGGER_HH_ */
Class for storing logger messages.
Definition: logger.hh:135
static StreamMask cout
Predefined mask of std::cout output.
Definition: logger.hh:52
int operator()(void)
Definition: logger.cc:54
std::stringstream cout_stream_
Store messages printed to cout output stream.
Definition: logger.hh:196
ArmaVec< double, N > vec
Definition: armor.hh:861
Logger & operator<<(Logger &log, StreamMask mask)
Definition: logger.cc:279
StreamMask streams_mask_
Mask of logger, specifies streams in actual time into which to be written.
Definition: logger.hh:207
StreamMask()
Empty constructor.
Definition: logger.hh:44
std::stringstream cerr_stream_
Store messages printed to cerr output stream.
Definition: logger.hh:197
std::string function_
Actual function.
Definition: logger.hh:203
StreamMask operator|(const StreamMask &other)
Definition: logger.cc:49
Logger & fmt(T &&...t)
Allow use functionality of fmtlib for formating message.
Definition: logger.hh:164
StreamMask(int mask)
Constructor set mask_ value.
Definition: logger.hh:48
static StreamMask cerr
Predefined mask of std::cerr output.
Definition: logger.hh:55
static StreamMask log
Predefined mask of log file output.
Definition: logger.hh:58
StreamMask operator&(const StreamMask &other)
Definition: logger.cc:44
Helper class, store mask specifying streams.
Definition: logger.hh:41
std::string date_time_
Actual date and time.
Definition: logger.hh:205
int mask_
Definition: logger.hh:70
bool every_process_
Flag marked if log message is printing for all processes or only for zero process.
Definition: logger.hh:201
int line_
Actual line.
Definition: logger.hh:204
std::stringstream file_stream_
Store messages printed to file.
Definition: logger.hh:198
StreamMask full_streams_mask_
Mask of logger, specifies all streams into which to be written in logger message. ...
Definition: logger.hh:208
std::string file_name_
Actual file.
Definition: logger.hh:202
int mpi_rank_
Actual process (if MPI is supported)
Definition: logger.hh:206
MsgType type_
Type of message.
Definition: logger.hh:200
#define THROW(whole_exception_expr)
Wrapper for throw. Saves the throwing point.
Definition: exceptions.hh:53
MsgType
Enum of types of Logger messages.
Definition: logger.hh:138