LogIt++
Header-only, macro-first C++ logging library
Loading...
Searching...
No Matches
tag_utils.hpp
Go to the documentation of this file.
1#pragma once
2#ifndef LOGIT_CPP_HEADER_LOGIT_CPP_LOGIT_UTILS_TAG_UTILS_HPP_INCLUDED
3#define LOGIT_CPP_HEADER_LOGIT_CPP_LOGIT_UTILS_TAG_UTILS_HPP_INCLUDED
4
5#include <sstream>
6#include <string>
7#include <initializer_list>
8#include <utility>
9
12
13namespace logit { namespace detail {
14
19 template <typename T>
20 inline std::string to_string_any(const T& v) {
21 std::ostringstream oss;
22 oss << v;
23 return oss.str();
24 }
25
30 inline std::pair<std::string,std::string> make_tag(std::string key, std::string value) {
31 return { std::move(key), std::move(value) };
32 }
33
39 template <typename V>
40 inline std::pair<std::string,std::string> make_tag(const char* key, const V& v) {
41 return { std::string(key), to_string_any(v) };
42 }
43
47 inline std::string format_tags(std::initializer_list<std::pair<std::string,std::string>> tags) {
48 if (tags.size() == 0) return {};
49 std::ostringstream oss;
50 oss << LOGIT_TAGS_JOIN;
51
52 bool first = true;
53 for (const auto& kv : tags) {
54 if (!first) oss << LOGIT_TAG_PAIR_SEP;
55 first = false;
56
57 const std::string& k = kv.first;
58 const std::string& v = kv.second;
59
60 auto need_quote = [] (const std::string& s) {
61 return s.find(' ') != std::string::npos ||
62 s.find('=') != std::string::npos;
63 };
64
65 oss << k << LOGIT_TAG_KV_SEP;
66# if LOGIT_TAG_QUOTE_VALUES
67 if (need_quote(v)) {
68 oss << '"';
69 for (char c : v) { if (c == '"') oss << '\\'; oss << c; }
70 oss << '"';
71 } else {
72 oss << v;
73 }
74# else
75 oss << v;
76# endif
77 }
78 return oss.str();
79 }
80
85 template <typename T>
86 inline std::string make_section(const T& name) {
87 return "[" + to_string_any(name) + "]";
88 }
89
90}} // namespace logit::detail
91
92#endif // LOGIT_CPP_HEADER_LOGIT_CPP_LOGIT_UTILS_TAG_UTILS_HPP_INCLUDED
#define LOGIT_TAG_PAIR_SEP
Separator between individual tag pairs (e.g., " " or "; ").
Definition config.hpp:195
#define LOGIT_TAG_KV_SEP
Separator between a tag key and its value.
Definition config.hpp:200
#define LOGIT_TAGS_JOIN
Separator inserted between the main message and the tag list (e.g., " | ").
Definition config.hpp:160
std::string to_string_any(const T &v)
Convert value to string via stream insertion.
Definition tag_utils.hpp:20
std::string format_tags(std::initializer_list< std::pair< std::string, std::string > > tags)
Format tag list into a single string.
Definition tag_utils.hpp:47
std::pair< std::string, std::string > make_tag(std::string key, std::string value)
Create tag from string key and value.
Definition tag_utils.hpp:30
std::string make_section(const T &name)
Format a raw section name as [name].
Definition tag_utils.hpp:86
The primary namespace for the LogIt++ library.