1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
#include <iostream>
#include <mutex>
#include <fstream>
namespace simpleLog {
inline bool log(std::ostream& out) {
return !!(out << std::endl);
}
template<typename T>
bool log(std::ostream& out, T&& value)
{
return !!(out << std::forward<T>(value) << std::endl);
}
template<typename First, typename ... Rest>
bool log(std::ostream& out, First&& first, Rest&& ... rest)
{
return !!(out << std::forward<First>(first)) && log(out, std::forward<Rest>(rest)...);
}
inline std::mutex logger_mtx;
class log_stream {
public:
log_stream(std::string_view str, std::ostream& ifile) : txt(str), file(ifile)
{
std::string s{ "[" };
txt = s + txt + "] ";
}
template <typename... Args>
bool operator() (Args&&... args) {
bool ok = log(file, std::forward<Args>(args)...);
{
std::lock_guard<std::mutex> lck(logger_mtx);
log(std::cout, txt, std::forward<Args>(args)...);
if (!ok)
log(std::cout, txt, "Error writing to log file");
}
return 0;
}
private:
std::string txt;
std::ostream& file;
};
}
int main()
{
std::ofstream file("log.txt");
simpleLog::log_stream log("->", file);
log("\nLast Night A DJ Saved My Life ", 777, "\nLast Night A DJ Saved My Life with a song");
return 0;
}
| |