如何在同一个程序中多次启动和关闭spdlog?

Kev*_*ude 3 c++ logging c++-cli spdlog

我使用 spdlog 在 Visual Studio 中运行托管和非托管代码的日志。出于这个原因,我编写了在底层使用 spdlog 的 shell 类。

但是,我的单元测试遇到了问题。我的单元测试在单个可执行文件中运行,因此我需要多次停止并重新启动 spdlog 记录器和日志文件。

我该怎么做呢?我在类中使用此代码当前启动 Windows DLL 中的 spdlog 实例:

private:
    API static std::mutex _mutex;
    API static std::shared_ptr<spdlog::logger> _instance;

    static std::shared_ptr<spdlog::logger> Instance()
    {
        std::unique_lock<std::mutex> lck(_mutex, std::defer_lock);
        lck.lock();
        if (_instance == nullptr)
        {
            _instance = spdlog::rotating_logger_mt("Logger", "EXO", 1024 * 1024 * 5, 4, true);
        }
        lck.unlock();
        return _instance;
    }
Run Code Online (Sandbox Code Playgroud)

Kev*_*ude 6

我从 spdlog 的创建者那里得到了这个答案。

来自如何在同一个程序中关闭和重新启动?去关机:

void Shutdown()
{
    spdlog::drop("Logger");
    delete _instance;
}
Run Code Online (Sandbox Code Playgroud)

然后就可以再次执行上面的创建过程了。

  • 这很好,但如果您使用shared_ptr,则不需要“delete”,因为单独的“drop”将删除shared_ptr引用,从而自动释放它。SpdLog 现在建议:`make_shared&lt;spdlog::async_logger&gt;(...)` (2认同)