74 lines
2.1 KiB
C++
74 lines
2.1 KiB
C++
#pragma once
|
||
#include <Logging/Logger.hpp>
|
||
#include <Logging/LoggerManager.hpp>
|
||
#include <Mod/Base.hpp>
|
||
#include <Mod/Registration.hpp>
|
||
#include <Mod/Context.hpp>
|
||
#include <memory>
|
||
#include <type_traits>
|
||
#include <typeinfo>
|
||
namespace vl::mod {
|
||
|
||
#if defined(__ELF__)
|
||
#define VL_MOD_SECTION __attribute__((section("vlmods"), used))
|
||
#else
|
||
#define VL_MOD_SECTION __attribute__((used))
|
||
#endif
|
||
|
||
template<class T>
|
||
class Mod : public Base {
|
||
|
||
protected:
|
||
std::shared_ptr<vl::logging::Logger> m_logger;
|
||
const vl::mod::Context& m_ctx;
|
||
|
||
private:
|
||
static std::unique_ptr<Base> _vl_factory(const Context& ctx) {
|
||
if constexpr (std::is_constructible_v<T, const Context&>)
|
||
{
|
||
return std::make_unique<T>(ctx);
|
||
}
|
||
else
|
||
{
|
||
static_assert(false, "Mod should have explicit constructor Mod(const vl::mod::Context& ctx) : ");
|
||
return std::make_unique<T>();
|
||
}
|
||
}
|
||
|
||
// Registration only stores a factory pointer — no early T usage.
|
||
static inline const Registration _vl_reg VL_MOD_SECTION {
|
||
kModRegMagic,
|
||
&_vl_factory
|
||
};
|
||
|
||
public:
|
||
explicit Mod(const vl::mod::Context& ctx)
|
||
: m_ctx(ctx)
|
||
{
|
||
// Automatically create per-mod combined logger
|
||
auto& mgr = vl::logging::LoggerManager::instance();
|
||
|
||
// Create log file in ctx.logDir, using mod’s name as prefix
|
||
|
||
auto name = std::string(static_cast<const T*>(this)->name());
|
||
auto logDir = m_ctx.logDir / name;
|
||
std::filesystem::create_directories(logDir);
|
||
m_logger = mgr.createCombined(
|
||
std::move(name),
|
||
std::move(logDir),
|
||
10 * 1024 * 1024, // example rotation size
|
||
vl::logging::Level::Info
|
||
);
|
||
|
||
m_logger->info("[{}] Mod constructed (v{})", static_cast<const T*>(this)->name(), static_cast<const T*>(this)->version());
|
||
}
|
||
|
||
virtual ~Mod() = default;
|
||
|
||
[[nodiscard]] auto& ctx() const noexcept { return m_ctx; }
|
||
[[nodiscard]] auto logger() const noexcept { return m_logger; }
|
||
[[nodiscard]] auto& loggerRef() const noexcept { return *m_logger; }
|
||
};
|
||
|
||
} // namespace vl::mod
|