userver: userver/logging/log_helper.hpp Source File
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
log_helper.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/logging/log_helper.hpp
4/// @brief @copybrief logging::LogHelper
5
6#include <chrono>
7#include <exception>
8#include <iosfwd>
9#include <iterator>
10#include <memory>
11#include <optional>
12#include <string_view>
13#include <system_error>
14#include <type_traits>
15
16#include <fmt/core.h>
17
18#include <userver/formats/common/meta.hpp>
19#include <userver/logging/fwd.hpp>
20#include <userver/logging/level.hpp>
21#include <userver/logging/log_extra.hpp>
22#include <userver/utils/impl/source_location.hpp>
23#include <userver/utils/meta.hpp>
24
25USERVER_NAMESPACE_BEGIN
26
27namespace logging {
28
29namespace impl {
30
31class TagWriter;
32
33struct Noop {};
34
35struct HexBase {
36 std::uint64_t value;
37
38 template <typename Unsigned, typename = std::enable_if_t<std::is_unsigned_v<Unsigned>>>
39 explicit constexpr HexBase(Unsigned value) noexcept : value(value) {
40 static_assert(sizeof(Unsigned) <= sizeof(value));
41 }
42
43 template <typename T>
44 explicit HexBase(T* pointer) noexcept : HexBase(reinterpret_cast<std::uintptr_t>(pointer)) {
45 static_assert(sizeof(std::uintptr_t) <= sizeof(value));
46 }
47};
48
49} // namespace impl
50
51/// Formats value in a hex mode with the fixed length representation.
52struct Hex final : impl::HexBase {
53 using impl::HexBase::HexBase;
54};
55
56/// Formats value in a hex mode with the shortest representation, just like
57/// std::to_chars does.
58struct HexShort final : impl::HexBase {
59 using impl::HexBase::HexBase;
60};
61
62/// Formats a string as quoted, escaping the '\' and '"' symbols.
63struct Quoted final {
64 std::string_view string;
65};
66
67enum class LogClass {
68 kLog,
69 kTrace,
70};
71
72/// Stream-like tskv-formatted log message builder.
73///
74/// Users can add LogHelper& operator<<(LogHelper&, ) overloads to use a faster
75/// localeless logging, rather than outputting data through the ostream
76/// operator.
77class LogHelper final {
78public:
79 /// @brief Constructs LogHelper with span logging
80 /// @param logger to log to
81 /// @param level message log level
82 /// @param log_class whether this LogHelper will be used to write a log record or a span
83 /// @param location source location that will be written to logs
85 LoggerRef logger,
86 Level level,
87 LogClass log_class = LogClass::kLog,
88 const utils::impl::SourceLocation& location = utils::impl::SourceLocation::Current()
89 ) noexcept;
90
91 /// @brief Constructs LogHelper with span logging
92 /// @param logger to log to (logging to nullptr does not output messages)
93 /// @param level message log level
94 /// @param log_class whether this LogHelper will be used to write a log record or a span
95 /// @param location source location that will be written to logs
97 const LoggerPtr& logger,
98 Level level,
99 LogClass log_class = LogClass::kLog,
100 const utils::impl::SourceLocation& location = utils::impl::SourceLocation::Current()
101 ) noexcept;
102
103 ~LogHelper();
104
105 LogHelper(LogHelper&&) = delete;
106 LogHelper(const LogHelper&) = delete;
107 LogHelper& operator=(LogHelper&&) = delete;
108 LogHelper& operator=(const LogHelper&) = delete;
109
110 // Helper function that could be called on LogHelper&& to get LogHelper&.
111 LogHelper& AsLvalue() noexcept { return *this; }
112
113 /// @cond
114 LogHelper& AsLvalue(std::string_view msg) noexcept {
115 *this << msg;
116 return *this;
117 }
118 /// @endcond
119
120 /// @cond
121 template <typename... Args>
122 LogHelper& AsLvalue(fmt::format_string<Args...> fmt, Args&&... args) noexcept {
123 VFormat(fmt::string_view(fmt), fmt::make_format_args(args...));
124 return *this;
125 }
126 /// @endcond
127
128 bool IsLimitReached() const noexcept;
129
130 template <typename T>
131 LogHelper& operator<<(const T& value) {
132 if constexpr (std::is_constructible_v<std::string_view, T>) {
133 // noexcept if the conversion is noexcept
134 *this << std::string_view{value};
135 } else if constexpr (std::is_signed_v<T>) {
136 using LongLong = long long;
137 *this << LongLong{value};
138 } else if constexpr (std::is_unsigned_v<T>) {
139 using UnsignedLongLong = unsigned long long;
140 *this << UnsignedLongLong{value};
141 } else if constexpr (std::is_base_of_v<std::exception, T>) {
142 *this << static_cast<const std::exception&>(value);
143 } else if constexpr (meta::kIsOstreamWritable<T>) {
144 // may throw a non std::exception based exception
145 Stream() << value;
146 FlushStream();
147 } else if constexpr (meta::kIsRange<T> && !formats::common::kIsFormatValue<T>) {
148 // may throw a non std::exception based exception
149 PutRange(value);
150 } else {
151 static_assert(
152 !sizeof(T),
153 "Please implement logging for your type: "
154 "logging::LogHelper& operator<<(logging::LogHelper& lh, const T& value)"
155 );
156 }
157
158 return *this;
159 }
160
161 LogHelper& operator<<(char value) noexcept;
162 LogHelper& operator<<(std::string_view value) noexcept;
163 LogHelper& operator<<(float value) noexcept;
164 LogHelper& operator<<(double value) noexcept;
165 LogHelper& operator<<(long double value) noexcept;
166 LogHelper& operator<<(unsigned long long value) noexcept;
167 LogHelper& operator<<(long long value) noexcept;
168 LogHelper& operator<<(bool value) noexcept;
169 LogHelper& operator<<(const std::exception& value) noexcept;
170
171 /// Extends internal LogExtra
172 LogHelper& operator<<(const LogExtra& extra) noexcept;
173
174 /// Extends internal LogExtra
175 LogHelper& operator<<(LogExtra&& extra) noexcept;
176
177 LogHelper& operator<<(Hex hex) noexcept;
178
179 LogHelper& operator<<(HexShort hex) noexcept;
180
181 LogHelper& operator<<(Quoted value) noexcept;
182
183 LogHelper& PutTag(std::string_view key, const LogExtra::Value& value) noexcept;
184 LogHelper& PutSwTag(std::string_view key, std::string_view value) noexcept;
185
186 template <typename... Args>
187 LogHelper& Format(fmt::format_string<Args...> fmt, Args&&... args) noexcept;
188
189 /// @cond
190 // For internal use only!
191 operator impl::Noop() const noexcept { return {}; }
192
193 struct InternalTag;
194
195 // For internal use only!
196 impl::TagWriter GetTagWriter();
197
198 /// @endcond
199
200private:
201 friend class impl::TagWriter;
202
203 void DoLog() noexcept;
204
205 void InternalLoggingError(std::string_view message) noexcept;
206
207 void PutFloatingPoint(float value);
208 void PutFloatingPoint(double value);
209 void PutFloatingPoint(long double value);
210 void PutUnsigned(unsigned long long value);
211 void PutSigned(long long value);
212 void PutBoolean(bool value);
213 void Put(std::string_view value);
214 void Put(char value);
215
216 void PutRaw(std::string_view value_needs_no_escaping);
217 void PutException(const std::exception& ex);
218 void PutQuoted(std::string_view value);
219
220 void VFormat(fmt::string_view fmt, fmt::format_args args) noexcept;
221
222 template <typename T>
223 void PutRangeElement(const T& value);
224
225 template <typename T, typename U>
226 void PutMapElement(const std::pair<const T, U>& value);
227
228 template <typename T>
229 void PutRange(const T& range);
230
231 std::ostream& Stream();
232 void FlushStream();
233
234 class Impl;
235 std::unique_ptr<Impl> pimpl_;
236};
237
238inline LogHelper& operator<<(LogHelper& lh, std::error_code ec) {
239 lh << ec.category().name() << ':' << ec.value() << " (" << ec.message() << ')';
240 return lh;
241}
242
243template <typename T>
244LogHelper& operator<<(LogHelper& lh, const std::atomic<T>& value) {
245 return lh << value.load();
246}
247
248template <typename T>
249LogHelper& operator<<(LogHelper& lh, const T* value) noexcept {
250 if (value == nullptr) {
251 lh << std::string_view{"(null)"};
252 } else if constexpr (std::is_same_v<T, char>) {
253 lh << std::string_view{value};
254 } else {
255 lh << Hex{value};
256 }
257 return lh;
258}
259
260template <typename T>
261LogHelper& operator<<(LogHelper& lh, T* value) {
262 static_assert(
263 !std::is_function_v<T>,
264 "An attempt to log the function address is denied. If you really know what you're doing, cast it to void*."
265 );
266 return lh << static_cast<const T*>(value);
267}
268
269template <typename T>
270LogHelper& operator<<(LogHelper& lh, const std::optional<T>& value) {
271 if (value)
272 lh << *value;
273 else
274 lh << "(none)";
275 return lh;
276}
277
278template <class Result, class... Args>
279LogHelper& operator<<(LogHelper& lh, Result (*)(Args...)) {
280 static_assert(!sizeof(Result), "Outputting functions or std::ostream formatters is forbidden");
281 return lh;
282}
283
284LogHelper& operator<<(LogHelper& lh, std::chrono::system_clock::time_point tp);
285LogHelper& operator<<(LogHelper& lh, std::chrono::seconds value);
286LogHelper& operator<<(LogHelper& lh, std::chrono::milliseconds value);
287LogHelper& operator<<(LogHelper& lh, std::chrono::microseconds value);
288LogHelper& operator<<(LogHelper& lh, std::chrono::nanoseconds value);
289LogHelper& operator<<(LogHelper& lh, std::chrono::minutes value);
290LogHelper& operator<<(LogHelper& lh, std::chrono::nanoseconds value);
291LogHelper& operator<<(LogHelper& lh, std::chrono::hours value);
292
293template <typename T>
294void LogHelper::PutRangeElement(const T& value) {
295 if constexpr (std::is_constructible_v<std::string_view, T>) {
296 *this << Quoted{value};
297 } else {
298 *this << value;
299 }
300}
301
302template <typename T, typename U>
303void LogHelper::PutMapElement(const std::pair<const T, U>& value) {
304 PutRangeElement(value.first);
305 *this << ": ";
306 PutRangeElement(value.second);
307}
308
309template <typename T>
310void LogHelper::PutRange(const T& range) {
311 static_assert(meta::kIsRange<T>);
312 using std::begin;
313 using std::end;
314
315 static_assert(
316 !std::is_same_v<meta::RangeValueType<T>, char>,
317 "You should either manually convert type to 'std::string_view' or provide 'operator<<' specialization for your "
318 "type: 'logging::LogHelper& operator<<(logging::LogHelper& lh, const T& value)' or make your type convertible "
319 "to 'std::string_view'"
320 );
321
322 constexpr std::string_view kSeparator = ", ";
323 *this << '[';
324
325 bool is_first = true;
326 auto curr = begin(range);
327 const auto end_iter = end(range);
328
329 while (curr != end_iter) {
330 if (IsLimitReached()) {
331 break;
332 }
333 if (is_first) {
334 is_first = false;
335 } else {
336 *this << kSeparator;
337 }
338
339 if constexpr (meta::kIsMap<T>) {
340 PutMapElement(*curr);
341 } else {
342 PutRangeElement(*curr);
343 }
344 ++curr;
345 }
346
347 const auto extra_elements = std::distance(curr, end_iter);
348
349 if (extra_elements != 0) {
350 if (!is_first) {
351 *this << kSeparator;
352 }
353 *this << "..." << extra_elements << " more";
354 }
355
356 *this << ']';
357}
358
359template <typename... Args>
360LogHelper& LogHelper::Format(fmt::format_string<Args...> fmt, Args&&... args) noexcept {
361 VFormat(fmt::string_view(fmt), fmt::make_format_args(args...));
362 return *this;
363}
364
365} // namespace logging
366
367USERVER_NAMESPACE_END