#ifndef __CAE_LOG_H #define __CAE_LOG_H #include // For basic_ostream_sink #include // For basic_file_sink #include #include #include #include namespace logging { /// No-op filter for use as the default Filter on a Logger. Passes /// all messages. template struct null_filter : public std::unary_function { bool operator () (const Entry&) const { return true; } }; /// Sink that opens an output file and writes Entries to that file template struct basic_file_sink { std::ofstream m_file; bool m_flush; basic_file_sink (const std::string& filename, std::ios_base::openmode mode = std::ios_base::app, bool flush = true) : m_file (filename.c_str(), mode), m_flush (flush) {} void operator () (const Entry& entry) { m_file << entry << '\n'; if (m_flush) m_file.flush(); } }; /// Sink implementation that holds a reference to an ostream and /// writes Entries to that stream template struct basic_ostream_sink { std::ostream& m_os; bool m_flush; basic_ostream_sink (std::ostream& os, bool flush = true) : m_os (os), m_flush (flush) {} void operator () (const Entry& entry) { m_os << entry << '\n'; if (m_flush) m_os.flush(); } }; /// Basic Logger implementation. Contains a Filter and a list of /// Sinks to which to write Entries template class basic_logger { public: typedef Entry entry_type; typedef boost::function filter_type; typedef boost::function sink_type; typedef std::list sink_list; basic_logger () : m_filter (null_filter ()) {} basic_logger (const filter_type& filter) : m_filter (filter) {} template basic_logger (const filter_type& filter, Iter sink_begin, Iter sink_end) : m_filter (filter), m_sinks (sink_begin, sink_end) {} filter_type& filter () { return m_filter; } sink_list& sinks () { return m_sinks; } void is_enabled (const entry_type& entry) { return m_filter (entry); } void write (const entry_type& entry) { if (!m_sinks.empty() && m_filter(entry)) { for (typename sink_list::iterator i = m_sinks.begin (), e = m_sinks.end(); i != e; ++i) (*i) (entry); } } private: filter_type m_filter; std::list m_sinks; }; } // namespace logging #endif // macro guard