aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--log.h32
-rw-r--r--test/log.cc1
2 files changed, 26 insertions, 7 deletions
diff --git a/log.h b/log.h
index 6aca9ea..3e26501 100644
--- a/log.h
+++ b/log.h
@@ -75,6 +75,25 @@ constexpr inline Arg sanitize_fmt_args(Arg arg) {
return arg;
}
+template <std::size_t N>
+struct formatter {
+ template <typename... Args>
+ std::size_t operator()(char* str,
+ std::size_t size,
+ const char* fmt,
+ Args... args) {
+ static_assert(sizeof...(Args) == N, "");
+ return std::snprintf(str, size, fmt, args...);
+ }
+};
+
+template <>
+struct formatter<0> {
+ std::size_t operator()(char* str, std::size_t size, const char* fmt) {
+ return std::snprintf(str, size, "%s", fmt);
+ }
+};
+
// -- TIME STAMP HELPER --------------------------------------------------------
template <int UtcOffset = 0>
@@ -112,7 +131,7 @@ struct time_stamp {
// -- LOGGER -------------------------------------------------------------------
-template <bool WithTimestamp = true, size_t BufSize = 128>
+template <bool WithTimestamp = true, std::size_t BufSize = 128>
struct logger {
constexpr logger() = default;
constexpr logger(log_level lvl) : m_lvl{lvl} {}
@@ -134,11 +153,11 @@ struct logger {
// -- LOGGER IMPLEMENTATION ----------------------------------------------------
-template <bool WithTimestamp, size_t BufSize>
+template <bool WithTimestamp, std::size_t BufSize>
template <log_level L, typename... Args>
constexpr void logger<WithTimestamp, BufSize>::log(const char* fmt,
Args... args) {
- size_t pos{0};
+ std::size_t pos{0};
// Add timestamp if enabled.
if (WithTimestamp) {
@@ -160,10 +179,9 @@ constexpr void logger<WithTimestamp, BufSize>::log(const char* fmt,
// string literal as fmt string and hence the user controls the fmt string.
// Additionally, we sanitize the arguments to only allow explicitly specified
// argument types.
- //
- // NOLINTNEXTLINE
- pos += std::snprintf(m_buf + pos, BufSize - pos, fmt,
- detail::sanitize_fmt_args(args)...);
+ detail::formatter<sizeof...(Args)> formatter;
+ pos += formatter(m_buf + pos, BufSize - pos, fmt,
+ detail::sanitize_fmt_args(args)...);
assert(pos < BufSize);
// Ensure terminated with new line and null terminator.
diff --git a/test/log.cc b/test/log.cc
index c059ba8..7d8305d 100644
--- a/test/log.cc
+++ b/test/log.cc
@@ -4,6 +4,7 @@ int main() {
logging::logger<> mlog;
mlog.set_level(logging::kDbg0);
+ INFO(&mlog, "Hallo nofmt");
INFO(&mlog, "Hallo %d", 42);
WARN(&mlog, "Hallo %x", 0x1337);
FAIL(&mlog, "Hallo %u", 666);