magpie
Loading...
Searching...
No Matches
Logger.hpp
1#pragma once
2
3#include <functional>
4#include <iostream>
5#include <string_view>
6#include <format>
7
8namespace magpie::logger {
9
10enum class Level {
11 debug,
12 info,
13 warning,
14 error,
15 critical
16};
17
18inline void defaultHandler(Level level, const std::string_view& message) {
19 switch (level) {
20 case Level::debug:
21 printf("DEBUG %.*s\n", static_cast<int>(message.length()), message.data());
22 break;
23 case Level::info:
24 printf("INFO %.*s\n", static_cast<int>(message.length()), message.data());
25 break;
26 case Level::warning:
27 printf("WARNING %.*s\n", static_cast<int>(message.length()), message.data());
28 break;
29 case Level::error:
30 printf("ERROR %.*s\n", static_cast<int>(message.length()), message.data());
31 break;
32 case Level::critical:
33 printf("CRITICAL %.*s\n", static_cast<int>(message.length()), message.data());
34 break;
35 }
36}
37
39 std::function<void(logger::Level, const std::string_view&)> logger = logger::defaultHandler;
40};
41
42inline LoggerConfig& config() {
43 static LoggerConfig conf;
44 return conf;
45}
46
47template <Level level, class... Args>
48inline void log(const std::format_string<Args...>& fmt, Args&&... args) {
49 // TODO: do I add a prefix?
50 auto& logger = config().logger;
51 if (!logger) {
52 return;
53 }
54 logger(
55 level, std::format(fmt, std::forward<Args>(args)...)
56 );
57}
58
59template <class... Args>
60inline void debug(const std::format_string<Args...>& format, Args&&... args) {
61 log<Level::debug, Args...>(format, std::forward<Args>(args)...);
62}
63
64template <class... Args>
65inline void info(const std::format_string<Args...>& format, Args&&... args) {
66 log<Level::info, Args...>(format, std::forward<Args>(args)...);
67}
68
69template <class... Args>
70inline void warn(const std::format_string<Args...>& format, Args&&... args) {
71 log<Level::warning, Args...>(format, std::forward<Args>(args)...);
72}
73
74template <class... Args>
75inline void error(const std::format_string<Args...>& format, Args&&... args) {
76 log<Level::error, Args...>(format, std::forward<Args>(args)...);
77}
78
79template <class... Args>
80inline void critical(const std::format_string<Args...>& format, Args&&... args) {
81 log<Level::critical, Args...>(format, std::forward<Args>(args)...);
82}
83
84}
Definition Logger.hpp:38