humanus.cpp/logger.cpp

42 lines
1.6 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include "logger.h"
#include <sstream>
#include <iomanip>
namespace humanus {
std::shared_ptr<spdlog::logger> define_log_level(spdlog::level::level_enum print_level,
spdlog::level::level_enum logfile_level,
std::string name) {
_print_level = print_level;
auto current_date = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(current_date);
std::stringstream ss;
std::tm tm_info = *std::localtime(&in_time_t);
ss << std::put_time(&tm_info, "%Y%m%d");
std::string formatted_date = ss.str(); // YYYYMMDD
std::string log_name = name.empty() ? formatted_date : name + "_" + formatted_date;
std::string log_file_path = (PROJECT_ROOT / "logs" / (log_name + ".log")).string();
// 确保日志目录存在
std::filesystem::create_directories(PROJECT_ROOT / "logs");
// 重置日志输出
std::shared_ptr<spdlog::logger> _logger = std::make_shared<spdlog::logger>(log_name);
// 添加标准错误输出sink相当于Python中的sys.stderr
auto stderr_sink = std::make_shared<spdlog::sinks::stderr_color_sink_mt>();
stderr_sink->set_level(print_level);
_logger->sinks().push_back(stderr_sink);
// 添加文件sink相当于Python中的PROJECT_ROOT / f"logs/{log_name}.log"
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(log_file_path, false);
file_sink->set_level(logfile_level);
_logger->sinks().push_back(file_sink);
return _logger;
}
} // namespace humanus