75 lines
2.0 KiB
C++
75 lines
2.0 KiB
C++
#ifndef LOG_HPP
|
|
#define LOG_HPP
|
|
|
|
#define log _log // comment to disable logging
|
|
|
|
#ifdef log
|
|
#include <zlib.h>
|
|
|
|
#define LOG_FILE_LOCATION "linuxSmartie.log.gz"
|
|
|
|
#include <chrono>
|
|
#include <mutex>
|
|
#include <print>
|
|
#include <string_view>
|
|
|
|
inline std::mutex cmtx; // console logging mutex
|
|
inline std::mutex fmtx; // file logging mutex
|
|
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 pattern = "[{}{}{}] ";
|
|
std::string_view color = "";
|
|
|
|
switch (level) {
|
|
case LOG::INF:
|
|
color = "\033[1;32m";
|
|
break; // bold; green
|
|
case LOG::WRN:
|
|
color = "\033[1;33m"; // bold; yellow
|
|
break;
|
|
case LOG::ERR:
|
|
color = "\033[1;31m"; // bold; red
|
|
break;
|
|
case LOG::DBG:
|
|
break;
|
|
case LOG::START:
|
|
color = "\033[1;3;5;36m"; // bold; italics; blinking; cyan
|
|
break;
|
|
}
|
|
|
|
/* log to console */
|
|
{
|
|
std::scoped_lock lock(cmtx);
|
|
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();
|
|
auto local = std::chrono::current_zone()->to_local(now);
|
|
std::string msg = std::format("{:%x %H:%M:%S }", floor<std::chrono::milliseconds>(local)); // 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
|
|
|
|
std::scoped_lock lock (fmtx);
|
|
gzFile file = gzopen(LOG_FILE_LOCATION, "ab");
|
|
if (file) {
|
|
gzprintf(file, "%s\n", msg.c_str());
|
|
gzclose(file);
|
|
}
|
|
}
|
|
}
|
|
|
|
#else
|
|
|
|
#define log(...)
|
|
|
|
#endif
|
|
|
|
#endif
|