58 lines
1.6 KiB
C++
58 lines
1.6 KiB
C++
#include "logger/logger.hpp"
|
|
#include <cassert>
|
|
#include <filesystem>
|
|
#include <fstream>
|
|
#include <sstream>
|
|
#include <string>
|
|
|
|
namespace fs = std::filesystem;
|
|
|
|
static std::string read_file(const fs::path& p) {
|
|
std::ifstream in(p);
|
|
std::stringstream ss;
|
|
ss << in.rdbuf();
|
|
return ss.str();
|
|
}
|
|
|
|
int main() {
|
|
const fs::path log_path = "logs/test_logger.log";
|
|
if (fs::exists(log_path)) fs::remove(log_path);
|
|
|
|
// 同步模式便于立即断言文件内容
|
|
Logger::Init(log_path.string(), 1, 2, /*is_async=*/false);
|
|
|
|
// 1) 默认 logger 可用
|
|
auto def = Logger::GetDefaultLogger();
|
|
assert(def != nullptr);
|
|
|
|
// 2) 全局级别设置生效
|
|
Logger::SetGlobalLevel(spdlog::level::debug);
|
|
assert(def->level() == spdlog::level::debug);
|
|
|
|
// 3) 模块 logger 创建 + 复用
|
|
auto net1 = Logger::GetModuleLogger("net");
|
|
auto net2 = Logger::GetModuleLogger("net");
|
|
assert(net1 != nullptr);
|
|
assert(net1.get() == net2.get());
|
|
|
|
// 4) 模块级别独立设置
|
|
Logger::SetModuleLevel("net", spdlog::level::warn);
|
|
assert(net1->level() == spdlog::level::warn);
|
|
|
|
// 5) 写日志并落盘
|
|
LOG_INFO("hello {}", "logger");
|
|
LOG_DEBUG("debug value = {}", 123);
|
|
net1->error("net module error {}", 7);
|
|
def->flush();
|
|
net1->flush();
|
|
|
|
assert(fs::exists(log_path));
|
|
std::string content = read_file(log_path);
|
|
assert(content.find("hello logger") != std::string::npos);
|
|
assert(content.find("debug value = 123") != std::string::npos);
|
|
assert(content.find("net module error 7") != std::string::npos);
|
|
|
|
Logger::Shutdown();
|
|
return 0;
|
|
}
|