logger.h
1 /*
2  * MoMEMta: a modular implementation of the Matrix Element Method
3  * Copyright (C) 2016 Universite catholique de Louvain (UCL), Belgium
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 // Heavily inspired by spdlog, Copyright(c) 2015 Gabi Melman
20 
21 #pragma once
22 
23 #include <momemta/impl/logger/common.h>
24 #include <momemta/impl/logger/formatter.h>
25 #include <momemta/impl/logger/sink.h>
26 
27 #include <sstream>
28 #include <vector>
29 
30 namespace logger {
31 
32 class logger {
33 public:
34  logger(sink_ptr single_sink);
35 
36  virtual ~logger();
37  logger(const logger&) = delete;
38  logger& operator=(const logger&) = delete;
39 
40  bool should_log(logging::level::level_enum) const;
41  void set_level(logging::level::level_enum);
42  logging::level::level_enum level() const;
43 
44  void set_formatter(formatter_ptr);
45 
46  // automatically call flush() if message level >= log_level
47  void flush_on(logging::level::level_enum log_level);
48 
49  virtual void flush();
50 
51  const std::vector<sink_ptr>& sinks() const;
52 
53  template <typename T> void log(logging::level::level_enum lvl, T&&);
54 
55 protected:
56 
57  virtual void _sink_it(details::log_msg&);
59  bool _should_flush_on(const details::log_msg&);
60 
61  std::vector<sink_ptr> _sinks;
62  formatter_ptr _formatter;
63  level_t _level;
64  level_t _flush_level;
65  std::atomic_size_t _index;
66 };
67 
69 public:
70  ostream_wrapper(logger& l, logging::level::level_enum lvl);
71 
72  virtual ~ostream_wrapper();
73  ostream_wrapper(const ostream_wrapper&) = delete;
74  ostream_wrapper& operator=(const ostream_wrapper&) = delete;
75 
76  template <typename T> friend ostream_wrapper& operator<<(ostream_wrapper& w, T&& msg) {
77  w._stream << msg;
78 
79  return w;
80  }
81 
82  bool valid();
83  void destroy();
84 
85 private:
86  bool _valid;
87  ::logger::logger& _logger;
88  ::logging::level::level_enum _lvl;
89  std::ostringstream _stream;
90 };
91 
92 logger_ptr get();
93 
94 }
95 
96 template <typename T>
97 void ::logger::logger::log(logging::level::level_enum lvl, T&& msg) {
98 
99  if (!should_log(lvl))
100  return;
101 
102  ::logger::details::log_msg log_msg(lvl);
103  log_msg.index = _index.fetch_add(1, std::memory_order_relaxed);
104  log_msg.raw << msg;
105  _sink_it(log_msg);
106 }