diff --git a/src/logger.h b/src/logger.h index e202787..d4bbfd9 100644 --- a/src/logger.h +++ b/src/logger.h @@ -1,12 +1,16 @@ #ifndef LOGGER_H #define LOGGER_H +#include #include #include +#include #include #include #include +using namespace std::chrono; + inline const std::string log_file = "iris.log"; enum class Level { INFO, WARNING, ERROR }; @@ -24,12 +28,16 @@ enum class Level { INFO, WARNING, ERROR }; } } +[[nodiscard]] inline const std::string formatted_time(const time_point& time) { + const auto now = round(time); + return std::format("[{:%y-%m-%d %H:%M:%S}]", now); +} + template concept Streamable = requires(std::ostream& out, T in) { { out << in } -> std::convertible_to; }; -// TODO: Add date/time stamp to log template inline void log(Level lvl, T msg) { if (std::getenv("RAWTERM_DEBUG") != nullptr) { @@ -38,7 +46,7 @@ inline void log(Level lvl, T msg) { std::ofstream out; out.open(log_file, std::ios::app); - out << level_str(lvl) << " " << msg << "\n"; + out << formatted_time(system_clock::now()) << level_str(lvl) << " " << msg << "\n"; out.close(); } diff --git a/tests/logger_test.cpp b/tests/logger_test.cpp index 904eedd..203b784 100644 --- a/tests/logger_test.cpp +++ b/tests/logger_test.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include "file_io.h" @@ -12,6 +13,19 @@ TEST_CASE("level_str", "[LOGGER]") { REQUIRE(level_str(Level::WARNING) == "[WARNING]"); } +TEST_CASE("formatted_time", "[LOGGER]") { + const std::string given_time = formatted_time(system_clock::now()); + + REQUIRE(given_time.size() == 19); + + REQUIRE(given_time.at(0) == '['); + REQUIRE(given_time.at(18) == ']'); + REQUIRE_THAT(std::stof(given_time.substr(1, 2)), Catch::Matchers::WithinAbs(0.0, 31.0)); + REQUIRE_THAT(std::stof(given_time.substr(3, 2)), Catch::Matchers::WithinAbs(0.0, 12.0)); + REQUIRE_THAT(std::stof(given_time.substr(10, 2)), Catch::Matchers::WithinAbs(0.0, 23.0)); + REQUIRE_THAT(std::stof(given_time.substr(10, 2)), Catch::Matchers::WithinAbs(0.0, 59.0)); +} + TEST_CASE("log", "[LOGGER]") { unsetenv("RAWTERM_DEBUG"); @@ -24,8 +38,8 @@ TEST_CASE("log", "[LOGGER]") { std::string contents_str = std::string(file_contents.value().begin(), file_contents.value().end()); - std::string expected = "[INFO] hello world"; - REQUIRE_THAT(contents_str, Catch::Matchers::ContainsSubstring(expected)); + REQUIRE_THAT(contents_str, Catch::Matchers::ContainsSubstring("INFO")); + REQUIRE_THAT(contents_str, Catch::Matchers::ContainsSubstring("hello world")); } SECTION("Given level") { @@ -37,8 +51,8 @@ TEST_CASE("log", "[LOGGER]") { std::string contents_str = std::string(file_contents.value().begin(), file_contents.value().end()); - std::string expected = "[WARNING] hello world"; - REQUIRE(contents_str.find(expected) != std::string::npos); + REQUIRE_THAT(contents_str, Catch::Matchers::ContainsSubstring("WARNING")); + REQUIRE_THAT(contents_str, Catch::Matchers::ContainsSubstring("hello world")); } setenv("RAWTERM_DEBUG", "True", 1);