add logging to file

This commit is contained in:
Drath
2025-10-05 16:32:13 +02:00
parent b515668b0d
commit 0bdc5e5472

View File

@@ -1,39 +1,56 @@
#ifndef LOG_HPP
#define LOG_HPP
// #define PATTERN "[{}{}{}] "
#include <zlib.h>
#include <chrono>
#include <mutex>
#include <print>
#include <string_view>
enum class LOG { INF, WRN, ERR, DBG };
inline std::mutex mtx;
enum class LOG { INF, WRN, ERR, DBG, START };
template <typename... Args>
inline void log(LOG level, std::string_view tag, std::format_string<Args...> str, Args&&... args) {
constexpr bool logToFile = true;
constexpr std::string_view reset = "\033[0m";
constexpr std::string_view green = "\033[32m";
constexpr std::string_view yellow = "\033[33m";
constexpr std::string_view red = "\033[31m";
constexpr std::string_view pattern = "[{}{}{}] ";
constexpr std::string_view pattern = "[{}{}{}] ";
std::string_view color = "";
std::scoped_lock lock(mtx);
switch (level) {
case LOG::INF:
std::print(pattern, green, tag, reset);
break;
color = "\033[1;32m";
break; // bold; green
case LOG::WRN:
std::print(pattern, yellow, tag, reset);
color = "\033[1;33m"; // bold; yellow
break;
case LOG::ERR:
std::print(pattern, red, tag, reset);
color = "\033[1;31m"; // bold; red
break;
case LOG::START:
color = "\033[1;3;5;36m"; // bold; italics; blinking; cyan
break;
default:
std::print(pattern, "", tag, "");
}
std::scoped_lock lock(mtx);
/* log to console */
std::print(pattern, color, tag, reset);
std::println(str, std::forward<Args>(args)...);
/* log to file */
if (logToFile) {
auto now = std::chrono::system_clock::now();
std::string msg = std::format("{:%x %H:%M:%S }", floor<std::chrono::milliseconds>(now)); // timestamp
std::format_to(std::back_inserter(msg), pattern, color, tag, reset); // tag
std::format_to(std::back_inserter(msg), str, std::forward<Args>(args)...); // actual log message
gzFile file = gzopen("linuxSmartie.log.gz", "ab");
if (file) {
gzprintf(file, "%s\n", msg.c_str());
gzclose(file);
}
}
}
#endif