Skip to content

Instantly share code, notes, and snippets.

@jemand2001
Created August 6, 2023 19:45
Show Gist options
  • Select an option

  • Save jemand2001/703645cc81be3938abbf75b0a7d22a29 to your computer and use it in GitHub Desktop.

Select an option

Save jemand2001/703645cc81be3938abbf75b0a7d22a29 to your computer and use it in GitHub Desktop.
tiny logging function (colors, source location, no macros)
#include <format>
#include <iostream>
#include <source_location>
#include <string_view>
#include <tuple>
#include <unordered_map>
enum class LogLevel { DEBUG, INFO, WARNING, ERROR, CRITICAL };
namespace CLIColors {
constexpr auto Reset = "\e[0m";
namespace Foreground {
constexpr auto Yellow = "\e[33m";
constexpr auto Gray = "\e[90m";
constexpr auto Blue = "\e[34m";
constexpr auto Red = "\e[31m";
constexpr auto Cyan = "\e[36m";
} // namespace Foreground
namespace Background {
constexpr auto Red = "\e[41m";
}
} // namespace CLIColors
const std::unordered_map<LogLevel, std::pair<const char *, const char *>>
levels = {{LogLevel::DEBUG, {CLIColors::Foreground::Gray, "DEBUG "}},
{LogLevel::INFO, {CLIColors::Foreground::Blue, "INFO "}},
{LogLevel::WARNING, {CLIColors::Foreground::Yellow, "WARNING "}},
{LogLevel::ERROR, {CLIColors::Foreground::Red, "ERROR "}},
{LogLevel::CRITICAL, {CLIColors::Background::Red, "CRITICAL"}}};
void log(const LogLevel level,
const std::string_view message,
std::source_location location = std::source_location::current()) {
auto [level_color, level_text] = levels.at(level);
std::cerr << std::format(
"[{}{}{}] [{}{}:{}:{}{}] (in {}) {}\n", level_color, level_text,
CLIColors::Reset, CLIColors::Foreground::Cyan, location.file_name(),
location.line(), location.column(), CLIColors::Reset,
location.function_name(), message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment