multisink.cpp 1.93 KB
Newer Older
1
#include "spdlog/sinks/basic_file_sink.h"
gabime's avatar
gabime committed
2
#include "spdlog/sinks/stdout_sinks.h"
gabime's avatar
gabime committed
3
#include "spdlog/spdlog.h"
davide's avatar
davide committed
4 5 6
#include <iostream>
#include <memory>

gabime's avatar
gabime committed
7
int main(int, char *[])
davide's avatar
davide committed
8 9 10 11 12 13 14 15
{
    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;
gabime's avatar
gabime committed
16
        sinks.push_back(std::make_shared<spdlog::sinks::stdout_sink_mt>());
17 18
        sinks.push_back(std::make_shared<spdlog::sinks::basic_file_sink_mt>("./log_regular_file.txt"));
        sinks.push_back(std::make_shared<spdlog::sinks::basic_file_sink_mt>("./log_debug_file.txt"));
davide's avatar
davide committed
19

gabime's avatar
gabime committed
20 21
        spdlog::logger console_multisink("multisink", sinks.begin(), sinks.end());
        console_multisink.set_level(spdlog::level::warn);
davide's avatar
davide committed
22

gabime's avatar
gabime committed
23 24 25
        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.
davide's avatar
davide committed
26 27 28

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

gabime's avatar
gabime committed
29
        if (enable_debug)
davide's avatar
davide committed
30
        {
gabime's avatar
gabime committed
31 32 33
            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
davide's avatar
davide committed
34 35 36 37 38 39 40
        }
        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)
41
    catch (const spdlog::spdlog_ex &ex)
davide's avatar
davide committed
42 43 44 45 46
    {
        std::cout << "Log init failed: " << ex.what() << std::endl;
        return 1;
    }
}