Here is the starter kit for the idea that I discussed in the comments. You will need to decide what to do with the errors written to the disk file - return false, exclude throw, or something else. I edited it to return true / false. Truth means no error. Work in progress.
#include <iostream>
#include <mutex>
#include <string>
#include <fstream>
#include <string_view>
#include <iomanip>
namespace dj {
inline bool print(std::ostream& out) {
return !!(out << std::endl);
}
template<typename T>
bool print(std::ostream& out, T&& value)
{
return !!(out << std::forward<T>(value) << std::endl);
}
template<typename First, typename ... Rest>
bool print(std::ostream& out, First&& first, Rest&& ... rest)
{
return !!(out << std::forward<First>(first)) && print(out, std::forward<Rest>(rest)...);
}
inline std::mutex logger_mtx;
class log_stream {
public:
log_stream(std::string_view str, std::ostream& ifile)
: name(str)
, file(ifile)
{
std::string s{ "[" };
name = s + name + "] ";
}
template <typename... Args>
bool operator() (Args&&... args) {
bool OK = print(file, std::forward<Args>(args)...);
{
std::lock_guard<std::mutex> lck(logger_mtx);
print(std::cout, name, std::forward<Args>(args)...);
if (!OK) {
print(std::cout, name, "-- Error writing to log file. --");
}
}
return OK;
}
private:
std::string name;
std::ostream& file;
};
}
int main()
{
std::ofstream outfile("DerivationOne.log.txt");
dj::log_stream log("DerivationOne", outfile);
std::ofstream outfile2;
dj::log_stream log2("DerivationTwo", outfile2);
log("Life. See ", 42, ", meaning of.");
bool OK =
log2("log", std::setw(4), 2.01, " That all, folks. -", 30, '-');
std::cout << (OK ? "OK" : "So not OK") << std::endl;
}
source
share