Using spdlog in a C++ project

Tree structure of the project.

The code of main.cc.
#include <iostream>
#include "spdlog/spdlog.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"

void do_work_in_another_file();
void rotating_example()
{
    try
    {
        // Create a file rotating logger with 5 MB size max and 3 rotated files
        auto max_size = 1048576 * 5;
        auto max_files = 3;

        // Set output time pattern
        // %f: Time accurate to microseconds
        // %n: Output mode "some_logger_name"
        // %l: Prints the severity level of the log message. Example include info, warn, error, debug or critical.
        // %v:  Prints the actual text or payload of the log message that you passed to the function.
        spdlog::set_pattern("[%Y-%m-%d %H:%M:%S.%f] [%n] [%l] %v");

        // Set it as default so you can spdlog::info() directly.
        auto logger = spdlog::rotating_logger_mt("some_logger_name",
                "logs/rotating.txt", max_size, max_files);

        logger->info("This is a log message that will trigger rotation once the file is full.");

        } catch (const spdlog::spdlog_ex& ex){
            std::cerr << "Log initialization failed:" << ex.what() << std::endl;
    }
}

int main(void)
{
    rotating_example();
    do_work_in_another_file();
    return 0;
}

The code of test.cc.
#include "spdlog/spdlog.h"

void do_work_in_another_file()
{
    // Get the logger by its registered name
    auto logger = spdlog::get("some_logger_name");
    if (logger) {
        logger->info("This message come from another file!");
    }
}
The output log:

Comments

Popular posts from this blog

BdsDex: failed to load Boot0001 "UEFI BHYVE SATA DISK BHYVE-OABE-20A5-E582" from PciRoot(0x0)/Pci (0x2, 0x0)/Stat(0x0,0xFFFF,0x0) : Not Found

FFmpeg

Install v2ray on FreeBSD