multisink.cpp 1.88 KB
Newer Older
davide's avatar
davide committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#include "spdlog/spdlog.h"

#include <iostream>
#include <memory>

namespace spd = spdlog;
int main(int, char*[])
{
    bool enable_debug = true;
    try
    {
        // This other example use a single logger with multiple sinks.
        // This means that the same log_msg is forwarded to multiple sinks;
        // Each sink can have it's own log level and a message will be logged.
        std::vector<spdlog::sink_ptr> sinks;
        sinks.push_back( std::make_shared<spdlog::sinks::stdout_sink_mt>() );
        sinks.push_back( std::make_shared<spdlog::sinks::simple_file_sink_mt>("./log_regular_file.txt") );
        sinks.push_back( std::make_shared<spdlog::sinks::simple_file_sink_mt>("./log_debug_file.txt") );

        spdlog::logger console_multisink("multisink",  sinks.begin(), sinks.end() );
        console_multisink.set_level( spdlog::level::warn);

        sinks[0]->set_level( spdlog::level::trace);  // console. Allow everything.  Default value
        sinks[1]->set_level( spdlog::level::trace);  //  regular file. Allow everything.  Default value
        sinks[2]->set_level( spdlog::level::off);    //  regular file. Ignore everything.

        console_multisink.warn("warn: will print only on console and regular file");

        if( enable_debug )
        {
            console_multisink.set_level( spdlog::level::debug); // level of the logger
            sinks[1]->set_level( spdlog::level::debug);  // regular file
            sinks[2]->set_level( spdlog::level::debug);  // debug file
        }
        console_multisink.debug("Debug: you should see this on console and both files");

        // Release and close all loggers
        spdlog::drop_all();
    }
    // Exceptions will only be thrown upon failed logger or sink construction (not during logging)
    catch (const spd::spdlog_ex& ex)
    {
        std::cout << "Log init failed: " << ex.what() << std::endl;
        return 1;
    }
}