Reputation: 809
I made a logger using spdlog which I use all over my program. But I also want to flush everything to a log file when the program is completed. How can I achieve this? I'm new to spdlog and I couldn't find proper documentation suitable for my situation.
Here are my file's:
Log.h:
#pragma once
#include "spdlog/spdlog.h"
#include "spdlog/fmt/ostr.h"
namespace Engine{
class Log{
public:
static void init();
inline static std::shared_ptr<spdlog::logger>& GetCoreLoger() { return s_CoreLogger; }
inline static std::shared_ptr<spdlog::logger>& GetClientLogger () { return s_ClientLogger;}
// I want something like this:
void flush_to_file();
private:
static std::shared_ptr<spdlog::logger> s_CoreLogger;
static std::shared_ptr<spdlog::logger> s_ClientLogger;
};
}
//Client log macros
#define VI_TRACE(...) ::Engine::Log::GetClientLogger()->trace(__VA_ARGS__)
#define VI_INFO(...) ::Engine::Log::GetClientLogger()->info(__VA_ARGS__)
#define VI_WARN(...) ::Engine::Log::GetClientLogger()->warn(__VA_ARGS__)
#define VI_ERROR(...) ::Engine::Log::GetClientLogger()->error(__VA_ARGS__)
Log.cpp:
#include "spdlog/sinks/stdout_color_sinks.h"
namespace Engine {
std::shared_ptr<spdlog::logger> Log::s_CoreLogger;
std::shared_ptr<spdlog::logger> Log::s_ClientLogger;
void Log::init() {
spdlog::set_pattern("%^[%T] %n: %v%$");
s_CoreLogger = spdlog::stdout_color_mt("VIO");
s_CoreLogger->set_level(spdlog::level::trace);
s_ClientLogger = spdlog::stdout_color_mt("APP");
s_ClientLogger->set_level(spdlog::level::trace);
}
// This is what I want:
void Log::flush_to_file(){
spdlog::write_to_file(); // Something like this
}
};
I want everything that spdlog have logged so far to be written into the file when I call that function. Is this possible? If so how can I do it?
Upvotes: 1
Views: 4159
Reputation: 367
What you probably need it is a multisink logger, a sink for stdout as you already have and a new one to also log to a file.
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
auto basic_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("mylog.log");
std::vector<spdlog::sink_ptr> sinks{console_sink, basic_sink};
auto logger = std::make_shared<spdlog::logger>("main", sinks.begin(), sinks.end());
spdlog::register_logger(logger); //if it would be used in some other place
Your function flush_to_file
probably should call
logger->flush();
To see the file content before the logger shutdown or automatic flush, try to add:
logger->flush_on(spdlog::level::info);
Upvotes: 3