Flow123d  release_2.2.0-914-gf1a3a4f
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 key '" << key_name << "' in Record '" << rec->type_name() << "'." << "\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  * Logger message can be created by more than one line ("\n" can be used multiple
116  * times):
117  *
118  @code
119  MessageOut() << "Start time: " << this->start_time() << "\n" << "End time: " << this->end_time() << "\n";
120  @endcode
121  *
122  * Or Logger allow using fmtlib functionality for simpler formatting of message:
123  *
124  @code
125  MessageOut() << fmt::format("Start time: {}\nEnd time: {}\n", this->start_time(), this->end_time());
126  MessageOut().fmt("Start time: {}\nEnd time: {}\n", this->start_time(), this->end_time());
127  @endcode
128  *
129  * In some cases message can be printed for all processes:
130  *
131  @code
132  MessageOut().every_proc() << "Size distributed at process: " << distr->lsize() << "\n";
133  @endcode
134  *
135  * Implementation of Logger does not support manipulator std::endl. Please, use "\n" instead.
136  */
137 class Logger : public std::ostream {
138 public:
139  /// Enum of types of Logger messages.
140  enum MsgType {
141  warning = 0,
142  message = 1,
143  log = 2,
144  debug = 3,
145  error = 4
146  };
147 
148  /// Return string value of given MsgType in full or shorter format (e.g. "WARNING" of "Wrn")
149  static const std::string msg_type_string(MsgType msg_type, bool full_format = true);
150 
151  /// Constructor.
152  Logger(MsgType type);
153 
154  /// Stores values for printing out line number, function, etc
155  Logger& set_context(const char* file_name, const char* function, const int line);
156 
157  /// Set flag every_process_ to true
158  Logger& every_proc();
159 
160  /**
161  * @brief Allow use functionality of fmtlib for formating message.
162  *
163  * See examples in description of Logger class.
164  */
165  template<class... T>
166  Logger& fmt(T&&... t)
167  {
168  try {
169  return *this << fmt::format(std::forward<T>(t)...);
170  } catch (const fmt::FormatError & e) {
171  THROW(ExcMessage() << EI_Message("FormatError: " + std::string(e.what())));
172  }
173  }
174 
175  /// Destructor.
176  ~Logger();
177 
178 
179 private:
180  /// Set @p streams_mask_ according to the type of message.
181  void set_mask();
182 
183  /// Print formated message to given screen stream if mask corresponds with @p streams_mask_.
184  void print_to_screen(std::ostream& stream, std::stringstream& scr_stream, StreamMask mask);
185 
186  /// Print formated message to given file stream if mask corresponds with @p streams_mask_.
187  void print_to_file(std::ofstream& stream, std::stringstream& file_stream, StreamMask mask);
188 
189  /// Print header to screen stream, helper method called from \p print_to_screen.
190  bool print_screen_header(std::ostream& stream, std::stringstream& scr_stream);
191 
192  /// Print header to file stream, helper method called from \p print_to_file.
193  void print_file_header(std::ofstream& stream, std::stringstream& file_stream);
194 
195  /// Return compact (relative) path to the given source file.
196  std::string compact_file_name(std::string file_name);
197 
198  std::stringstream cout_stream_; ///< Store messages printed to cout output stream
199  std::stringstream cerr_stream_; ///< Store messages printed to cerr output stream
200  std::stringstream file_stream_; ///< Store messages printed to file
201 
202  MsgType type_; ///< Type of message.
203  bool every_process_; ///< Flag marked if log message is printing for all processes or only for zero process.
204  std::string file_name_; ///< Actual file.
205  std::string function_; ///< Actual function.
206  int line_; ///< Actual line.
207  std::string date_time_; ///< Actual date and time.
208  int mpi_rank_; ///< Actual process (if MPI is supported)
209  StreamMask streams_mask_; ///< Mask of logger, specifies streams in actual time into which to be written
210  StreamMask full_streams_mask_; ///< Mask of logger, specifies all streams into which to be written in logger message
211 
212  template <class T>
213  friend Logger &operator<<(Logger & log, const T & x);
214  friend Logger &operator<<(Logger & log, std::ostream & (*pf) (std::ostream &) );
215  friend Logger &operator<<(Logger & log, StreamMask mask);
216 };
217 
218 
219 Logger &operator<<(Logger & log, StreamMask mask);
220 
221 
222 Logger &operator<<(Logger & log, std::ostream & (*pf) (std::ostream &) );
223 
224 
225 template <class T>
226 Logger &operator<<(Logger & log, const T & x)
227 {
228  if ( (log.streams_mask_ & StreamMask::cout)() ) log.cout_stream_ << x;
229  if ( (log.streams_mask_ & StreamMask::cerr)() ) log.cerr_stream_ << x;
230  if ( (log.streams_mask_ & StreamMask::log )() ) log.file_stream_ << x;
231  return log;
232 }
233 
234 
235 
236 
237 
238 
239 /// Internal macro defining universal record of log
240 #define _LOG(type) \
241  Logger( type ).set_context( __FILE__, __func__, __LINE__)
242 /// Macro defining 'message' record of log
243 #define MessageOut() \
244  _LOG( Logger::MsgType::message )
245 /// Macro defining 'warning' record of log
246 #define WarningOut() \
247  _LOG( Logger::MsgType::warning )
248 /// Macro defining 'log' record of log
249 #define LogOut() \
250  _LOG( Logger::MsgType::log )
251 /// Macro defining 'debug' record of log
252 #define DebugOut() \
253  _LOG( Logger::MsgType::debug )
254 
255 /**
256  * Print variable name and value.
257  * Usage:
258  * DebugOut() << print_var(x) << print_var(y)
259  */
260 #define print_var(var) \
261  std::string(#var) << "=" << (var) << ", "
262 
263 
264 
265 
266 #endif /* LOGGER_HH_ */
Class for storing logger messages.
Definition: logger.hh:137
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:198
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:209
StreamMask()
Empty constructor.
Definition: logger.hh:44
std::stringstream cerr_stream_
Store messages printed to cerr output stream.
Definition: logger.hh:199
std::string function_
Actual function.
Definition: logger.hh:205
StreamMask operator|(const StreamMask &other)
Definition: logger.cc:49
Logger & fmt(T &&...t)
Allow use functionality of fmtlib for formating message.
Definition: logger.hh:166
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:207
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:203
int line_
Actual line.
Definition: logger.hh:206
std::stringstream file_stream_
Store messages printed to file.
Definition: logger.hh:200
StreamMask full_streams_mask_
Mask of logger, specifies all streams into which to be written in logger message. ...
Definition: logger.hh:210
std::string file_name_
Actual file.
Definition: logger.hh:204
int mpi_rank_
Actual process (if MPI is supported)
Definition: logger.hh:208
MsgType type_
Type of message.
Definition: logger.hh:202
#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:140