logger.h

#pragma once

#include <memory>

#include "spdlog/spdlog.h"

namespace sunny {
class logger final {
public:
    static logger& instance();

    logger(const logger&) = delete;

    logger& operator=(const logger&) = delete;

private:
    logger() = default;

    ~logger() = default;

public:
    bool start(unsigned int file_level, unsigned int console_level, std::string_view name, std::string_view log_file,
               std::string_view pattern = "%C-%m-%d %T [%n:%^%L%$:%t] %v");

    std::shared_ptr<spdlog::logger> get();

private:
    std::shared_ptr<spdlog::logger> logger_;
};

#define LOG_DEBUG sunny::logger::instance().get()->debug
#define LOG_INFO sunny::logger::instance().get()->info
#define LOG_WARN sunny::logger::instance().get()->warn
#define LOG_ERROR sunny::logger::instance().get()->error
}  // namespace sunny

logger.cc

#include "logger.h"

#include <memory>
#include <vector>

#include "spdlog/sinks/daily_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"

namespace sunny {
logger& logger::instance() {
    static logger object;
    return object;
}

bool logger::start(unsigned int file_level, unsigned int console_level, std::string_view name,
                   std::string_view log_file, std::string_view pattern) {
    // file logger
    auto file_log_level = static_cast<spdlog::level::level_enum>(file_level);
    auto file_logger = std::make_shared<spdlog::sinks::daily_file_sink_mt>(log_file.data(), 0, 0);
    file_logger->set_level(file_log_level);

    std::vector<spdlog::sink_ptr> sinks;
    sinks.push_back(file_logger);

    // console logger
    auto console_log_level = static_cast<spdlog::level::level_enum>(console_level);
    auto console_logger = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
    console_logger->set_level(console_log_level);
    sinks.push_back(console_logger);

    auto logger = std::make_shared<spdlog::logger>(name.data(), begin(sinks), end(sinks));
    logger->set_level(spdlog::level::trace);
    spdlog::register_logger(logger);

    // set option
    logger->set_pattern(pattern.data());

    spdlog::set_error_handler([](const std::string& msg) {
        LOG_ERROR("logger error handler: {}", msg);
    });

    logger_ = logger;

    return true;
}

std::shared_ptr<spdlog::logger> logger::get() {
    return logger_;
}
}  // namespace sunny