Files
mutil/include/Logging.hpp
2025-06-23 13:54:24 -04:00

89 lines
2.8 KiB
C++

//
// Created by maxine on 6/16/25.
//
#pragma once
#include <iostream>
#include <functional>
#include <format>
namespace Mutil::Logging {
/// Logger object for constructing loggers.
class LoggerObj {
private:
/// Output stream, default std::clog.
std::ostream &os = std::clog;
/// Lambda formatting function, primarily for storing a format string in a versatile way, users allowed to supply their own.
std::function<std::string(void)> λ;
public:
/// Default constructor, just simple messages to be written to console
LoggerObj() {};
/// Construct with specified output stream
LoggerObj(std::ostream &os);
/// Construct with a custom, formatted prefix applied to every message, such as "* Mutil Logging >> message".
template<typename... Args>
LoggerObj(const std::format_string<Args...> fmt, Args&&... args) {
λ = [fmt, args...](){
return std::vformat(fmt.get(), std::make_format_args(args...));
};
}
/// Construct with a custom lambda formatting function
LoggerObj(std::function<std::string(void)> λ) : λ(λ) {};
/// Construct with a specified output stream and custom formatting function
LoggerObj(std::ostream &os, std::function<std::string(void)> λ) : λ(λ) {};
public:
/// If provided only runs formatting function, formatting function may retrieve data for its own messages.
void operator()() {
λ && os << λ();
}
/// Send a simple log message
void operator()(const std::string_view message) {
(λ && os << λ() << message << '\n') ||
os << message << '\n';
}
/// Send a formatted/complex log message
template<typename... Args>
void operator()(const std::format_string<Args...> fmt, Args&&... args) {
(λ && os << λ() << std::vformat(fmt.get(), std::make_format_args(args...)) << '\n') ||
os << std::vformat(fmt.get(), std::make_format_args(args...)) << '\n';
};
/// Send log messages using logger as a stream
template<typename In>
std::ostream& operator<<(In message) {
(λ && os << λ() << message) ||
os << message;
return os;
};
};
class Info : public LoggerObj {
public:
Info() : LoggerObj("[I] | ") {};
};
class Warning : public LoggerObj {
public:
Warning() : LoggerObj("[W] | ") {};
};
class Error : public LoggerObj {
public:
Error() : LoggerObj("[E] | ") {};
};
class Verbose : public LoggerObj {
public:
Verbose() : LoggerObj("[V] | ") {};
};
class Debug : public LoggerObj {
public:
Debug() : LoggerObj("[D] | ") {};
};
}