Files
mutil/include/Logging.hpp

124 lines
3.7 KiB
C++

//
// Created by maxine on 6/16/25.
//
#pragma once
#include <iostream>
#include <sstream>
#include <functional>
#include <format>
namespace Mutil::Logging {
/// Logger object for constructing loggers.
class LoggerObj : public std::ostream {
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()> λPrefix;
std::function<std::string(const std::string_view)> λMessage;
//std::function<std::string(const std::string)> λMessage;
//std::function<std::string()> λSuffix;
public:
/// Default constructor, just simple messages to be written to console
LoggerObj() {};
/// Construct with specified output stream
LoggerObj(std::ostream &os) : os(os) {};
/// Full construction
LoggerObj(std::ostream &os, std::function<std::string(const std::string_view)> λMessage) : os(os), λMessage(λMessage) {};
/// Full construction
//LoggerObj(std::ostream &os,
// std::function<std::string()> λprefix,
// std::function<std::string(const std::string)> λmessage,
// std::function<std::string()> λsuffix
// ) : os(os), λPrefix(λprefix), λMessage(λmessage), λSuffix(λsuffix) {};
public:
/// Send a simple log message
//void operator()(const std::string_view message) {
void operator()(const std::string message) {
//std::ostringstream oss;
//λPrefix && os << λPrefix();
//(λMessage && os << λMessage(message)) || os << message;
//std::cout << λMessage(message);
//λSuffix && os << λSuffix();
//os << oss.str() << std::endl;
λMessage ? os << λMessage(message) : os << message;
os << std::endl;
}
/// Send a formatted/complex log message
template<typename... Args>
void operator()(const std::format_string<Args...> fmt, Args&&... args) {
//std::ostringstream oss;
std::string m = std::vformat(fmt.get(), std::make_format_args(args...));
//λPrefix && os << λPrefix();
//(λMessage && os << λMessage(m)) || os << m;
//λSuffix && os << λSuffix();
//os << oss.str() << std::endl;
λMessage ? os << λMessage(m) : os << m;
os << std::endl;
};
/// Send log messages using logger as a stream
template<typename In>
LoggerObj& operator<<(In message) {
//std::ostringstream oss;
//oss << message;
//operator()(oss.str());
//(λ && os << λ() << message) ||
//os << message;
//return os;
//λPrefix && os << λPrefix();
//(λMessage && os << λMessage(message)) || os << message;
λMessage ? os << λMessage(message) : os << message;
//λSuffix && os << λSuffix();
os << std::endl;
return *this;
};
};
/*
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] | ") {};
};
*/
}