userver: userver/logging/log_helper.hpp Source File
Loading...
Searching...
No Matches
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 template <typename... Args>
115 LogHelper& AsLvalue(fmt::format_string<Args...> fmt, Args&&... args) noexcept {
116 VFormat(fmt::string_view(fmt), fmt::make_format_args(args...));
117 return *this;
118 }
119 /// @endcond
120
121 bool IsLimitReached() const noexcept;
122
123 template <typename T>
124 LogHelper& operator<<(const T& value) {
125 if constexpr (std::is_constructible_v<std::string_view, T>) {
126 // noexcept if the conversion is noexcept
127 *this << std::string_view{value};
128 } else if constexpr (std::is_signed_v<T>) {
129 using LongLong = long long;
130 *this << LongLong{value};
131 } else if constexpr (std::is_unsigned_v<T>) {
132 using UnsignedLongLong = unsigned long long;
133 *this << UnsignedLongLong{value};
134 } else if constexpr (std::is_base_of_v<std::exception, T>) {
135 *this << static_cast<const std::exception&>(value);
136 } else if constexpr (meta::kIsOstreamWritable<T>) {
137 // may throw a non std::exception based exception
138 Stream() << value;
139 FlushStream();
140 } else if constexpr (meta::kIsRange<T> && !formats::common::kIsFormatValue<T>) {
141 // may throw a non std::exception based exception
142 PutRange(value);
143 } else {
144 VFormat("{}", fmt::make_format_args(value));
145 }
146
147 return *this;
148 }
149
150 LogHelper& operator<<(char value) noexcept;
151 LogHelper& operator<<(std::string_view value) noexcept;
152 LogHelper& operator<<(float value) noexcept;
153 LogHelper& operator<<(double value) noexcept;
154 LogHelper& operator<<(long double value) noexcept;
155 LogHelper& operator<<(unsigned long long value) noexcept;
156 LogHelper& operator<<(long long value) noexcept;
157 LogHelper& operator<<(bool value) noexcept;
158 LogHelper& operator<<(const std::exception& value) noexcept;
159
160 /// Extends internal LogExtra
161 LogHelper& operator<<(const LogExtra& extra) noexcept;
162
163 /// Extends internal LogExtra
164 LogHelper& operator<<(LogExtra&& extra) noexcept;
165
166 LogHelper& operator<<(Hex hex) noexcept;
167
168 LogHelper& operator<<(HexShort hex) noexcept;
169
170 LogHelper& operator<<(Quoted value) noexcept;
171
172 LogHelper& PutTag(std::string_view key, const LogExtra::Value& value) noexcept;
173 LogHelper& PutSwTag(std::string_view key, std::string_view value) noexcept;
174
175 /// @brief Formats a log message using the specified format string and arguments.
176 /// @param fmt The format string as per fmtlib.
177 /// @param args Arguments to be formatted into the log message.
178 /// @return A reference to the LogHelper object for chaining.
179 template <typename... Args>
180 LogHelper& Format(fmt::format_string<Args...> fmt, Args&&... args) noexcept;
181
182 /// @cond
183 // For internal use only!
184 operator impl::Noop() const noexcept { return {}; }
185
186 struct InternalTag;
187
188 // For internal use only!
189 impl::TagWriter GetTagWriter();
190
191 /// @endcond
192
193private:
194 friend class impl::TagWriter;
195
196 void DoLog() noexcept;
197
198 void InternalLoggingError(std::string_view message) noexcept;
199
200 void PutFloatingPoint(float value);
201 void PutFloatingPoint(double value);
202 void PutFloatingPoint(long double value);
203 void PutUnsigned(unsigned long long value);
204 void PutSigned(long long value);
205 void PutBoolean(bool value);
206 void Put(std::string_view value);
207 void Put(char value);
208
209 void PutRaw(std::string_view value_needs_no_escaping);
210 void PutException(const std::exception& ex);
211 void PutQuoted(std::string_view value);
212
213 void VFormat(fmt::string_view fmt, fmt::format_args args) noexcept;
214
215 template <typename T>
216 void PutRangeElement(const T& value);
217
218 template <typename T, typename U>
219 void PutMapElement(const std::pair<const T, U>& value);
220
221 template <typename T>
222 void PutRange(const T& range);
223
224 std::ostream& Stream();
225 void FlushStream();
226
227 class Impl;
228 std::unique_ptr<Impl> pimpl_;
229};
230
231inline LogHelper& operator<<(LogHelper& lh, std::error_code ec) {
232 lh << ec.category().name() << ':' << ec.value() << " (" << ec.message() << ')';
233 return lh;
234}
235
236template <typename T>
237LogHelper& operator<<(LogHelper& lh, const std::atomic<T>& value) {
238 return lh << value.load();
239}
240
241template <typename T>
242LogHelper& operator<<(LogHelper& lh, const T* value) noexcept {
243 if (value == nullptr) {
244 lh << std::string_view{"(null)"};
245 } else if constexpr (std::is_same_v<T, char>) {
246 lh << std::string_view{value};
247 } else {
248 lh << Hex{value};
249 }
250 return lh;
251}
252
253template <typename T>
254LogHelper& operator<<(LogHelper& lh, T* value) {
255 static_assert(
256 !std::is_function_v<T>,
257 "An attempt to log the function address is denied. If you really know what you're doing, cast it to void*."
258 );
259 return lh << static_cast<const T*>(value);
260}
261
262template <typename T>
263LogHelper& operator<<(LogHelper& lh, const std::optional<T>& value) {
264 if (value)
265 lh << *value;
266 else
267 lh << "(none)";
268 return lh;
269}
270
271template <typename Fun, typename = std::enable_if_t<std::is_invocable_r_v<void, Fun, LogHelper&>>>
272LogHelper& operator<<(LogHelper& lh, Fun&& value) {
273 std::forward<Fun>(value)(lh);
274 return lh;
275}
276
277template <class Result, class... Args>
278LogHelper& operator<<(LogHelper& lh, Result (*)(Args...)) {
279 static_assert(!sizeof(Result), "Outputting functions or std::ostream formatters is forbidden");
280 return lh;
281}
282
283LogHelper& operator<<(LogHelper& lh, std::chrono::system_clock::time_point tp);
284LogHelper& operator<<(LogHelper& lh, std::chrono::seconds value);
285LogHelper& operator<<(LogHelper& lh, std::chrono::milliseconds value);
286LogHelper& operator<<(LogHelper& lh, std::chrono::microseconds value);
287LogHelper& operator<<(LogHelper& lh, std::chrono::nanoseconds value);
288LogHelper& operator<<(LogHelper& lh, std::chrono::minutes value);
289LogHelper& operator<<(LogHelper& lh, std::chrono::nanoseconds value);
290LogHelper& operator<<(LogHelper& lh, std::chrono::hours value);
291
292template <typename T>
293void LogHelper::PutRangeElement(const T& value) {
294 if constexpr (std::is_constructible_v<std::string_view, T>) {
295 *this << Quoted{value};
296 } else {
297 *this << value;
298 }
299}
300
301template <typename T, typename U>
302void LogHelper::PutMapElement(const std::pair<const T, U>& value) {
303 PutRangeElement(value.first);
304 *this << ": ";
305 PutRangeElement(value.second);
306}
307
308template <typename T>
309void LogHelper::PutRange(const T& range) {
310 static_assert(meta::kIsRange<T>);
311 using std::begin;
312 using std::end;
313
314 static_assert(
315 !std::is_same_v<meta::RangeValueType<T>, char>,
316 "You should either manually convert type to 'std::string_view' or provide 'operator<<' specialization for your "
317 "type: 'logging::LogHelper& operator<<(logging::LogHelper& lh, const T& value)' or make your type convertible "
318 "to 'std::string_view'"
319 );
320
321 constexpr std::string_view kSeparator = ", ";
322 *this << '[';
323
324 bool is_first = true;
325 auto curr = begin(range);
326 const auto end_iter = end(range);
327
328 while (curr != end_iter) {
329 if (IsLimitReached()) {
330 break;
331 }
332 if (is_first) {
333 is_first = false;
334 } else {
335 *this << kSeparator;
336 }
337
338 if constexpr (meta::kIsMap<T>) {
339 PutMapElement(*curr);
340 } else {
341 PutRangeElement(*curr);
342 }
343 ++curr;
344 }
345
346 const auto extra_elements = std::distance(curr, end_iter);
347
348 if (extra_elements != 0) {
349 if (!is_first) {
350 *this << kSeparator;
351 }
352 *this << "..." << extra_elements << " more";
353 }
354
355 *this << ']';
356}
357
358template <typename... Args>
359LogHelper& LogHelper::Format(fmt::format_string<Args...> fmt, Args&&... args) noexcept {
360 VFormat(fmt::string_view(fmt), fmt::make_format_args(args...));
361 return *this;
362}
363
364} // namespace logging
365
366USERVER_NAMESPACE_END