Log/Log.h

85 lines
1.9 KiB
C
Raw Normal View History

2019-06-01 19:25:24 +02:00
#pragma once
2022-09-05 00:01:31 +02:00
#include <functional> // std::function
#include <sstream> // std::stringstream (buffer for log entries)
#include <string>
#include <vector>
2019-06-01 19:25:24 +02:00
2020-11-02 23:51:44 +01:00
#ifndef LOG_USEMUTEX
2020-11-20 22:04:05 +01:00
#define LOG_USEMUTEX 0
2020-11-02 23:51:44 +01:00
#endif
namespace Log {
enum class Level { off = 0, fatal, error, warn, note, info, debug, trace };
2019-06-01 19:25:24 +02:00
// set up the logger with a ConsoleOutput
void init();
// close all output streams
void stop();
2019-06-01 19:25:24 +02:00
void addLogfile(const std::string& filename, Level max, bool truncate = false);
void addLogfile(const std::string& filename, Level min, Level max, bool truncate = false);
2019-06-01 19:25:24 +02:00
void setConsoleLogLevel(Level lvl);
void setColoredOutput(bool enabled);
2019-06-01 19:25:24 +02:00
// Log entry that can be formed with various mixed data types
// by concatenation with the << operator
// Inspired from https://stackoverflow.com/a/8337882
class Entry {
private:
std::stringstream ss;
const Level lvl;
2019-06-01 19:25:24 +02:00
void addMetadataHeader();
2019-06-01 19:25:24 +02:00
2019-06-02 18:54:58 +02:00
public:
explicit Entry(Level lvl);
Entry(const Entry&) = delete;
Entry& operator=(const Entry&) = delete;
Entry(Entry&&) = default;
Entry& operator=(Entry&&) = default;
~Entry();
Level getLevel() const {
return lvl;
}
using MetaFunction = std::function<std::ostream&(std::ostream&, const Entry&)>;
template <typename T> Entry& operator<<(const T& msg) {
ss << msg;
return *this;
}
};
extern std::vector<Entry::MetaFunction> entryMetaFunctions;
std::ostream& defaultEntryMetaTime(std::ostream&, const Entry&);
std::ostream& defaultEntryMetaLevel(std::ostream&, const Entry&);
class LeveledSink {
private:
Level level;
public:
explicit LeveledSink(Level level) noexcept : level{level} {};
template <typename T> Entry operator<<(const T& msg) const {
Entry entry{level};
entry << msg;
return entry;
}
2019-06-01 19:25:24 +02:00
};
// LeveledSinks
extern const LeveledSink fatal;
extern const LeveledSink error;
extern const LeveledSink warn;
extern const LeveledSink note;
extern const LeveledSink info;
extern const LeveledSink debug;
extern const LeveledSink trace;
2020-09-23 21:02:31 +02:00
} // namespace Log