Skip to content

Instantly share code, notes, and snippets.

@rmartinho
Last active April 3, 2024 06:32
Show Gist options
  • Save rmartinho/5074263 to your computer and use it in GitHub Desktop.
Save rmartinho/5074263 to your computer and use it in GitHub Desktop.
Some lousy simple logger
// Internal Combustion Engine
//
// Written in 2012 by Martinho Fernandes <martinho.fernandes@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
// Expanding variadic packs of side-effects
// Usage:
// ICE_EXPAND_SIDE_EFFECTS(f(T))
#ifndef ICE_EXPAND_HPP
#define ICE_EXPAND_HPP
#include <initializer_list>
#define ICE_EXPAND_SIDE_EFFECTS(...) std::initializer_list<char>{ ((__VA_ARGS__), void(), 0) };
#endif // ICE_EXPAND_HPP
// Internal Combustion Engine
//
// Written in 2012 by Martinho Fernandes <martinho.fernandes@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
// Logging facilities
// Usage:
// ICE_LOG(ice::ftr, ice::cerr) << "some log statement";
#ifndef ICE_LOG_HPP
#define ICE_LOG_HPP
#include <expand.h++>
#include <sstream>
#include <string>
#include <initializer_list>
#include <iostream>
namespace ice {
namespace log {
enum level {
ftr, // debug
fyi, // info
wtf, // warning
omg, // error
fml, // fatal
};
template <typename Sink, level Level>
struct forwarder : Sink {
public:
~forwarder() { Sink::write(ss.str()); }
template <typename T>
forwarder& operator<<(T const& t) {
ss << t;
return *this;
}
private:
std::stringstream ss;
};
template <typename... Sinks>
struct sinks : private Sinks... {
void write(std::string const& str) {
ICE_EXPAND_SIDE_EFFECTS(Sinks::write(str));
}
};
struct cerr {
void write(std::string const& str) {
std::cerr << str << std::endl;
}
};
} // namespace log
} // namespace ice
#define ICE_LOG(LEVEL, ...) ::ice::log::forwarder< ::ice::log::sinks< __VA_ARGS__ >, LEVEL>{}
#endif // ICE_LOG_HPP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment