Add file logging to local application data directory

This commit is contained in:
Dan Paulat 2024-06-01 00:01:35 -05:00
parent 41d47878e3
commit 32cd672a40
6 changed files with 255 additions and 47 deletions

View file

@ -21,6 +21,7 @@ namespace Logger
{
void Initialize();
void AddFileSink(const std::string& baseFilename);
std::shared_ptr<spdlog::logger> Create(const std::string& name);
} // namespace Logger

View file

@ -3,6 +3,7 @@
#include <mutex>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/rotating_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
namespace scwx
@ -12,9 +13,34 @@ namespace util
namespace Logger
{
static const std::string logPattern_ = "[%Y-%m-%d %T.%e] [%t] [%^%l%$] [%n] %v";
static std::vector<std::shared_ptr<spdlog::sinks::sink>> extraSinks_ {};
void Initialize()
{
spdlog::set_pattern("[%Y-%m-%d %T.%e] [%t] [%^%l%$] [%n] %v");
spdlog::set_pattern(logPattern_);
}
void AddFileSink(const std::string& baseFilename)
{
constexpr std::size_t maxSize = 20u * 1024u * 1024u; // 20 MB
constexpr std::size_t maxFiles = 5u;
constexpr bool rotateOnOpen = true;
auto fileSink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
baseFilename, maxSize, maxFiles, rotateOnOpen);
fileSink->set_pattern(logPattern_);
spdlog::apply_all(
[&](std::shared_ptr<spdlog::logger> logger)
{
auto& sinks = logger->sinks();
sinks.push_back(fileSink);
});
extraSinks_.push_back(fileSink);
}
std::shared_ptr<spdlog::logger> Create(const std::string& name)
@ -26,6 +52,13 @@ std::shared_ptr<spdlog::logger> Create(const std::string& name)
std::shared_ptr<spdlog::logger> logger =
std::make_shared<spdlog::logger>(name, sink);
// Add additional registered sinks
for (auto& extraSink : extraSinks_)
{
auto& sinks = logger->sinks();
sinks.push_back(extraSink);
}
// Register the logger, so it can be retrieved later using spdlog::get()
spdlog::register_logger(logger);