|
| 1 | +#pragma once |
| 2 | + |
| 3 | +#include <optional> |
| 4 | +#include <lbd/fe/loc.h> |
| 5 | +#include <lbd/utils/term.h> |
| 6 | +#include <lbd/exceptions.h> |
| 7 | + |
| 8 | +namespace logs { |
| 9 | + struct Logger { |
| 10 | + bool exit_on_error = true; |
| 11 | + bool use_color = false; |
| 12 | + bool show_loc = true; |
| 13 | + |
| 14 | + Logger() = default; |
| 15 | + |
| 16 | + Logger(const bool exit_on_error, const bool use_color, const bool show_loc) : exit_on_error(exit_on_error), |
| 17 | + use_color(use_color), show_loc(show_loc) { |
| 18 | + if (use_color) { |
| 19 | + enable_virtual_terminal(); |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + template<typename... Args> |
| 24 | + [[noreturn]] void error(const std::optional<fe::loc::Loc> &loc, Args &&... args) const { |
| 25 | + if (use_color) { |
| 26 | + std::cerr << colors::RED; |
| 27 | + } |
| 28 | + if (show_loc && loc.has_value()) { |
| 29 | + std::cerr << loc.value() << ": "; |
| 30 | + } |
| 31 | + (std::cerr << ... << std::forward<Args>(args)); |
| 32 | + if (use_color) { |
| 33 | + std::cerr << colors::RESET; |
| 34 | + } |
| 35 | + std::cerr << std::endl; |
| 36 | + if (exit_on_error) { |
| 37 | + exit(EXIT_FAILURE); |
| 38 | + } |
| 39 | + throw ControlledExit{}; |
| 40 | + } |
| 41 | + |
| 42 | + template<typename... Args> |
| 43 | + void info(Args &&... args) const { |
| 44 | + log_impl(colors::BLUE, std::cout, std::forward<Args>(args)...); |
| 45 | + } |
| 46 | + |
| 47 | + template<typename... Args> |
| 48 | + void debug(Args &&... args) const { |
| 49 | + log_impl(colors::YELLOW, std::cout, std::forward<Args>(args)...); |
| 50 | + } |
| 51 | + |
| 52 | + private: |
| 53 | + template<typename... Args> |
| 54 | + void log_impl(const std::string &color, std::ostream &os, Args &&... args) const { |
| 55 | + if (use_color) { |
| 56 | + os << color; |
| 57 | + } |
| 58 | + (os << ... << std::forward<Args>(args)); |
| 59 | + if (use_color) { |
| 60 | + os << colors::RESET; |
| 61 | + } |
| 62 | + os << std::endl; |
| 63 | + } |
| 64 | + }; |
| 65 | +} |
0 commit comments