Flow123d  intersections_paper-476-gbe68821
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 <sstream>
24 #include <vector>
25 #include <string>
26 
27 
28 #include "system/fmt/format.h"
29 #include "system/exc_common.hh"
30 
31 
32 
33 /**
34  * @brief Helper class, store mask specifying streams
35  *
36  * Defines masks of all used streams as static methods and allows combining and comparing masks using
37  * the overloaded operators.
38  */
39 class StreamMask {
40 public:
41  /// Empty constructor
43  : mask_(0) {}
44 
45  /// Constructor set \p mask_ value
46  StreamMask(int mask)
47  : mask_(mask) {}
48 
49  /// Predefined mask of std::cout output
50  static StreamMask cout;
51 
52  /// Predefined mask of std::cerr output
53  static StreamMask cerr;
54 
55  /// Predefined mask of log file output
56  static StreamMask log;
57 
58  // Overload & operator
59  StreamMask operator &(const StreamMask &other);
60 
61  // Overload | operator
62  StreamMask operator |(const StreamMask &other);
63 
64  // Overload () operator
65  int operator()(void);
66 
67 private:
68  int mask_;
69 };
70 
71 
72 /**
73  * @brief Class for storing logger messages.
74  *
75  * Allow define different levels of log messages and distinguish output streams
76  * for individual leves. These output streams are -
77  * - standard console output (std::cout)
78  * - standard error output (std::cerr)
79  * - file output (see \p LoggerOptions class)
80  *
81  * Logger distinguishes four type of levels -
82  * - warning: printed to standard error and file output
83  * - message: printed to standard console and file output
84  * - log: printed to file output
85  * - debug: printed to file output (level is used only in debug mode)
86  *
87  * File output is optional. See \p LoggerOptions for setting this output stream.
88  *
89  * <b>Example of Logger usage:</b>
90  *
91  * For individual levels are defined macros -
92  * - MessageOut()
93  * - WarningOut()
94  * - LogOut()
95  * - DebugOut()
96  * that ensure display of actual code point (source file, line and function).
97  *
98  * Logger message is created by using an operator << and allow to add each type
99  * that has override this operator. Message is terminated with manipulator
100  * std::endl. Implicitly logger message is printed only in processor with rank
101  * zero. If necessary printed message for all process, it provides a method
102  * every_proc().
103  *
104  * Examples of logger messages formating:
105  *
106  @code
107  MessageOut() << "End of simulation at time: " << secondary_eq->solved_time() << "\n";
108  WarningOut() << "Unprocessed key '" << key_name << "' in Record '" << rec->type_name() << "'." << "\n";
109  LogOut() << "Write output to output stream: " << this->_base_filename << " for time: " << time << "\n";
110  DebugOut() << "Calling 'initialize' of empty equation '" << typeid(*this).name() << "'." << "\n";
111  @endcode
112  *
113  * Logger message can be created by more than one line ("\n" can be used multiple
114  * times):
115  *
116  @code
117  MessageOut() << "Start time: " << this->start_time() << "\n" << "End time: " << this->end_time() << "\n";
118  @endcode
119  *
120  * Or Logger allow using fmtlib functionality for simpler formatting of message:
121  *
122  @code
123  MessageOut() << fmt::format("Start time: {}\nEnd time: {}\n", this->start_time(), this->end_time());
124  MessageOut().fmt("Start time: {}\nEnd time: {}\n", this->start_time(), this->end_time());
125  @endcode
126  *
127  * In some cases message can be printed for all processes:
128  *
129  @code
130  MessageOut().every_proc() << "Size distributed at process: " << distr->lsize() << "\n";
131  @endcode
132  *
133  * Implementation of Logger does not support manipulator std::endl. Please, use "\n" instead.
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::ostream& stream, 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::ofstream& stream, 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  template <class T>
211  friend Logger &operator<<(Logger & log, const T & x);
212  friend Logger &operator<<(Logger & log, std::ostream & (*pf) (std::ostream &) );
213  friend Logger &operator<<(Logger & log, StreamMask mask);
214 };
215 
216 
217 Logger &operator<<(Logger & log, StreamMask mask);
218 
219 
220 Logger &operator<<(Logger & log, std::ostream & (*pf) (std::ostream &) );
221 
222 
223 template <class T>
224 Logger &operator<<(Logger & log, const T & x)
225 {
226  if ( (log.streams_mask_ & StreamMask::cout)() ) log.cout_stream_ << x;
227  if ( (log.streams_mask_ & StreamMask::cerr)() ) log.cerr_stream_ << x;
228  if ( (log.streams_mask_ & StreamMask::log )() ) log.file_stream_ << x;
229  return log;
230 }
231 
232 
233 
234 
235 
236 
237 /// Internal macro defining universal record of log
238 #define _LOG(type) \
239  Logger( type ).set_context( __FILE__, __func__, __LINE__)
240 /// Macro defining 'message' record of log
241 #define MessageOut() \
242  _LOG( Logger::MsgType::message )
243 /// Macro defining 'warning' record of log
244 #define WarningOut() \
245  _LOG( Logger::MsgType::warning )
246 /// Macro defining 'log' record of log
247 #define LogOut() \
248  _LOG( Logger::MsgType::log )
249 /// Macro defining 'debug' record of log
250 #define DebugOut() \
251  _LOG( Logger::MsgType::debug )
252 
253 /**
254  * Print variable name and value.
255  * Usage:
256  * DebugOut() << print_var(x) << print_var(y)
257  */
258 #define print_var(var) \
259  std::string(#var) << "=" << (var) << ", "
260 
261 
262 
263 
264 #endif /* LOGGER_HH_ */
Class for storing logger messages.
Definition: logger.hh:135
static StreamMask cout
Predefined mask of std::cout output.
Definition: logger.hh:50
int operator()(void)
Definition: logger.cc:54
std::stringstream cout_stream_
Store messages printed to cout output stream.
Definition: logger.hh:196
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:42
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:46
static StreamMask cerr
Predefined mask of std::cerr output.
Definition: logger.hh:53
static StreamMask log
Predefined mask of log file output.
Definition: logger.hh:56
StreamMask operator&(const StreamMask &other)
Definition: logger.cc:44
Helper class, store mask specifying streams.
Definition: logger.hh:39
std::string date_time_
Actual date and time.
Definition: logger.hh:205
int mask_
Definition: logger.hh:68
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:45
MsgType
Enum of types of Logger messages.
Definition: logger.hh:138