Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Import <fmt> and improve the logger class #7

Open
shlomnissan opened this issue Oct 8, 2024 · 0 comments
Open

Import <fmt> and improve the logger class #7

shlomnissan opened this issue Oct 8, 2024 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@shlomnissan
Copy link
Collaborator

We currently use macros for logging. We can enhance our logging experience by replacing these macros with std::source_location and utilizing the <fmt> library for string formatting. This approach allows us to forward string formatting parameters. Here's an implementation from another C++ library I'm working on for reference (note that it's using user-defined a user-defined deduction guide).

#pragma once

#include "engine/core/timer.hpp"

#include <filesystem>
#include <iostream>
#include <mutex>
#include <source_location>
#include <string>

#include <fmt/format.h>

namespace engine {

namespace fs = std::filesystem;

enum class LogLevel {
    Error,
    Warning,
    Info,
    Debug
};

class Logger {
public:
    template <typename... Args>
    struct Log {
        Log(
            LogLevel level,
            std::string_view format_str,
            Args&&... args,
            const std::source_location& loc = std::source_location::current())
        {
            const auto lock = std::scoped_lock(mutex_);

            auto& stream = level == LogLevel::Error ? std::cerr : std::cout;
            const auto path = fs::path{loc.file_name()};
            const auto message = fmt::format(fmt::runtime(format_str), args...);
            stream << fmt::format(
                "[{} -> {}:{}]{}: {}\n",
                Timer::GetTimestamp(),
                path.filename().string(),
                loc.line(),
                Logger::ToString(level),
                message
            );
        }
    };

    template <typename... Args>
    Log(LogLevel level, std::string_view message, Args&&...) -> Log<Args...>;

private:
    static std::mutex mutex_;

    [[nodiscard]] static auto ToString(LogLevel level) -> std::string;
};

}
@aliddell aliddell transferred this issue from acquire-project/acquire-driver-zarr Oct 8, 2024
@aliddell aliddell added the enhancement New feature or request label Oct 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
Status: Backlog
Development

No branches or pull requests

2 participants