94 lines
2.5 KiB
C++
94 lines
2.5 KiB
C++
#include "common/base/logging/logger.h"
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <filesystem>
|
|
#include <fstream>
|
|
#include <iterator>
|
|
#include <string>
|
|
|
|
#include <gtest/gtest.h>
|
|
#include <unistd.h>
|
|
|
|
namespace cmvr::logging {
|
|
namespace {
|
|
|
|
class LoggerTest : public testing::Test {
|
|
protected:
|
|
void SetUp() override
|
|
{
|
|
std::array<char, 64> pattern{};
|
|
const std::string value = "/tmp/cmvr-logger-test-XXXXXX";
|
|
std::copy(value.begin(), value.end(), pattern.begin());
|
|
if (char* created = ::mkdtemp(pattern.data())) {
|
|
directory_ = created;
|
|
}
|
|
ASSERT_FALSE(directory_.empty());
|
|
}
|
|
|
|
void TearDown() override
|
|
{
|
|
shutdownLogging();
|
|
std::error_code error;
|
|
std::filesystem::remove_all(directory_, error);
|
|
}
|
|
|
|
config::LoggerConfig warningFileConfig() const
|
|
{
|
|
config::LoggerConfig config;
|
|
config.set_minimum_level(config::LOG_LEVEL_DEBUG);
|
|
config.set_directory(directory_.string());
|
|
config.set_flush_interval_seconds(3600);
|
|
auto* route = config.add_routes();
|
|
route->set_level(config::LOG_LEVEL_WARNING);
|
|
route->set_terminal(false);
|
|
route->set_file(true);
|
|
return config;
|
|
}
|
|
|
|
std::string fileContents() const
|
|
{
|
|
std::ifstream input(directory_ / "logger_test.log");
|
|
return {std::istreambuf_iterator<char>(input),
|
|
std::istreambuf_iterator<char>()};
|
|
}
|
|
|
|
std::filesystem::path directory_;
|
|
};
|
|
|
|
TEST_F(LoggerTest, ExplicitFlushMakesWarningVisibleInFile)
|
|
{
|
|
ASSERT_TRUE(initLogging(
|
|
warningFileConfig(), "logger_test", directory_));
|
|
|
|
Logger::instance().write(
|
|
Level::WARNING, __FILE__, __LINE__, "warning sentinel");
|
|
Logger::instance().flush();
|
|
|
|
EXPECT_NE(fileContents().find("warning sentinel"), std::string::npos);
|
|
}
|
|
|
|
TEST_F(LoggerTest, ErrorIsVisibleInFileImmediately)
|
|
{
|
|
auto config = warningFileConfig();
|
|
config.mutable_routes(0)->set_level(config::LOG_LEVEL_ERROR);
|
|
ASSERT_TRUE(initLogging(config, "logger_test", directory_));
|
|
|
|
Logger::instance().write(
|
|
Level::ERROR, __FILE__, __LINE__, "error sentinel");
|
|
|
|
EXPECT_NE(fileContents().find("error sentinel"), std::string::npos);
|
|
}
|
|
|
|
TEST_F(LoggerTest, FlushIsSafeOutsideInitializedLifetime)
|
|
{
|
|
Logger::instance().flush();
|
|
ASSERT_TRUE(initLogging(
|
|
warningFileConfig(), "logger_test", directory_));
|
|
shutdownLogging();
|
|
Logger::instance().flush();
|
|
}
|
|
|
|
} // namespace
|
|
} // namespace cmvr::logging
|