userver: userver/tracing/span.hpp Source File
Loading...
Searching...
No Matches
span.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/tracing/span.hpp
4/// @brief @copybrief tracing::Span
5
6#include <optional>
7#include <string_view>
8
9#include <userver/logging/log.hpp>
10#include <userver/logging/log_extra.hpp>
11#include <userver/tracing/scope_time.hpp>
12#include <userver/tracing/tracer_fwd.hpp>
13#include <userver/utils/impl/internal_tag.hpp>
14#include <userver/utils/impl/source_location.hpp>
15
16USERVER_NAMESPACE_BEGIN
17
18namespace tracing {
19
20class SpanBuilder;
21struct SpanEvent;
22
23/// @brief Measures the execution time of the current code block, links it with
24/// the parent tracing::Spans and stores that info in the log.
25///
26/// Logging of spans can be controlled at runtime via @ref USERVER_NO_LOG_SPANS, provided that you
27/// `Append` @ref components::LoggingConfigurator component or use @ref components::CommonComponentList.
28///
29/// See @ref scripts/docs/en/userver/logging.md for usage examples and more
30/// descriptions.
31///
32/// @warning Shall be created only as a local variable. Do not use it as a
33/// class member!
34class Span final {
35public:
36 class Impl;
37
38 /// Use implicit task-local storage for parent identification, takes TraceID and Link from the parent `Span`.
39 ///
40 /// For extremely rare cases where a new Trace ID is required, use @ref tracing::Span::MakeSpan.
41 explicit Span(
42 std::string name,
43 const utils::impl::SourceLocation& source_location = utils::impl::SourceLocation::Current()
44 );
45
46 /// Sets an arbitrary `Span` as parent. If `parent == nullptr`, then creates a root `Span`.
47 ///
48 /// Useful in extremely rare cases. Prefer the constructor above by default.
49 explicit Span(
50 std::string name,
51 const Span* parent,
52 ReferenceType reference_type = ReferenceType::kChild,
53 const utils::impl::SourceLocation& source_location = utils::impl::SourceLocation::Current()
54 );
55
56 Span(Span&& other) noexcept;
57 Span(const Span& other) = delete;
58 Span& operator=(Span&&) = delete;
59 Span& operator=(const Span&) = delete;
60 ~Span();
61
62 /// @brief Returns the Span of the current task.
63 ///
64 /// Should not be called in non-coroutine
65 /// context. Should not be called from a task with no alive Span.
66 ///
67 /// Rule of thumb: it is safe to call it from a task created by
68 /// utils::Async/utils::CriticalAsync/utils::PeriodicTask. If current task was
69 /// created with an explicit engine::impl::*Async(), you have to create a Span
70 /// beforehand.
71 static Span& CurrentSpan();
72
73 /// @brief Returns nullptr if called in non-coroutine context or from a task
74 /// with no alive Span; otherwise returns the Span of the current task.
75 static Span* CurrentSpanUnchecked();
76
77 /// Factory function for extremely rare cases of creating a Span with custom
78 /// IDs; prefer Span constructor instead.
79 ///
80 /// @return A new Span with the specified IDs.
81 /// @param name Name of a new Span.
82 /// @param trace_id New Trace ID; if empty then the Trace ID is autogenerated.
83 /// @param parent_span_id ID of the parent Span, can be empty.
84 /// @param source_location Implementation detail, do not touch.
85 static Span MakeSpan(
86 std::string name,
87 std::string_view trace_id,
88 std::string_view parent_span_id,
89 const utils::impl::SourceLocation& source_location = utils::impl::SourceLocation::Current()
90 );
91
92 /// Factory function for extremely rare cases of creating a Span with custom
93 /// IDs; prefer Span constructor instead.
94 ///
95 /// @return A new Span with the specified IDs.
96 /// @param name Name of a new Span.
97 /// @param trace_id New Trace ID; if empty then the Trace ID is autogenerated.
98 /// @param parent_span_id ID of the parent Span, can be empty.
99 /// @param link The new Link; if empty the Link is autogenerated.
100 /// @param source_location Implementation detail, do not touch.
101 static Span MakeSpan(
102 std::string name,
103 std::string_view trace_id,
104 std::string_view parent_span_id,
105 std::string_view link,
106 const utils::impl::SourceLocation& source_location = utils::impl::SourceLocation::Current()
107 );
108
109 /// Factory function for rare cases of creating a root Span that starts
110 /// the trace_id chain, ignoring `CurrentSpan`, if any. Useful
111 /// in background jobs, periodics, distlock tasks, cron tasks, etc.
112 /// The result of such jobs is not directly requested by anything.
113 ///
114 /// @return A new Span that is the root of a new Span hierarchy.
115 /// @param name Name of a new Span
116 /// @param source_location Implementation detail, do not touch.
117 static Span MakeRootSpan(
118 std::string name,
119 const utils::impl::SourceLocation& source_location = utils::impl::SourceLocation::Current()
120 );
121
122 /// Create a child which can be used independently of the parent.
123 ///
124 /// The child shares no state with its parent. If you need to run code in
125 /// parallel, create a child span and use the child in a separate task.
127 std::string name,
128 const utils::impl::SourceLocation& source_location = utils::impl::SourceLocation::Current()
129 ) const;
130
131 Span CreateFollower(
132 std::string name,
133 const utils::impl::SourceLocation& source_location = utils::impl::SourceLocation::Current()
134 ) const;
135
136 /// @brief Creates a tracing::ScopeTime attached to the span.
137 ScopeTime CreateScopeTime();
138
139 /// @brief Creates a tracing::ScopeTime attached to the Span and starts
140 /// measuring execution time.
141 /// Tag `{scope_name}_time` with elapsed time is added to result span.
142 ///
143 /// @note `name` parameter is expected to satisfy snake case.
144 /// Otherwise, it is converted to snake case.
145 ScopeTime CreateScopeTime(std::string name);
146
147 /// Returns total time elapsed for a certain scope of this span.
148 /// If there is no record for the scope, returns 0.
149 ScopeTime::Duration GetTotalDuration(const std::string& scope_name) const;
150
151 /// Returns total time elapsed for a certain scope of this span.
152 /// If there is no record for the scope, returns 0.
153 ///
154 /// Prefer using Span::GetTotalDuration()
155 ScopeTime::DurationMillis GetTotalElapsedTime(const std::string& scope_name) const;
156
157 /// Add a tag that is used on each logging in this Span and all
158 /// future children.
159 void AddTag(std::string key, logging::LogExtra::Value value);
160
161 /// Add a tag that is used on each logging in this Span and all
162 /// future children. It will not be possible to change its value.
163 void AddTagFrozen(std::string key, logging::LogExtra::Value value);
164
165 /// Add a tag that is local to the Span (IOW, it is not propagated to
166 /// future children) and logged only once in the destructor of the Span.
167 void AddNonInheritableTag(std::string key, logging::LogExtra::Value value);
168
169 /// @overload AddNonInheritableTag
170 void AddNonInheritableTags(const logging::LogExtra&);
171
172 /// Add an event to Span.
173 void AddEvent(SpanEvent&& event);
174
175 /// Add an event (without attributes) to Span.
176 /// @overload AddEvent
177 void AddEvent(std::string_view event_name);
178
179 /// @brief Sets log level with which the current span itself is written into the tracing
180 /// system.
181 ///
182 /// This (mostly) does not affect logs written within the span,
183 /// unlike @ref tracing::Span::SetLocalLogLevel.
184 ///
185 /// If `Span`'s log level is less than the global logger's log level, then the span is
186 /// not written out. In that case:
187 /// * nested logs are still written to the logging system;
188 /// * they inherit `trace_id`, `link` and `span_id` of the nearest *written* `Span` object;
189 /// * tags are still inherited from the *nearest* `Span` even if it is hidden;
190 /// * this allows to use `Span`s as tag scopes regardless of their tracing purposes.
191 ///
192 /// Tracing systems use span's log level to highlight `warning` and `error` spans.
193 void SetLogLevel(logging::Level log_level);
194
195 /// See @ref tracing::Span::SetLogLevel.
197
198 /// @brief Sets an additional cutoff for the logs written in the scope of this `Span`,
199 /// and in nested scopes recursively.
200 ///
201 /// For example, if the global log level is `info`, and the current `Span` has
202 /// (own or inherited) local log level `warning`, then all `LOG_INFO`s within the current
203 /// scope will be thrown away.
204 ///
205 /// The cutoff also applies to the span itself. If the @ref tracing::Span::SetLogLevel "span's log level"
206 /// is less than the local log level, then the span is not written to the tracing system.
207 ///
208 /// Local log level of child spans can override local log level of parent spans in both directions.
209 /// For example:
210 /// * if local log level of a parent `Span` is `warning`,
211 /// * and local log level of a child span is set `info`,
212 /// * then `info` logs within that `Span` will be written,
213 /// * as long as the global log level is not higher than `info`.
214 ///
215 /// Currently, local log level cannot override the global log level of the logger.
216 /// For example, if the global log level is `info`, and the current `Span` has
217 /// (own or inherited) local log level `debug`, then all `LOG_DEBUG`s within the current
218 /// scope will **still** be thrown away.
219 void SetLocalLogLevel(std::optional<logging::Level> log_level);
220
221 /// See @ref tracing::Span::SetLocalLogLevel.
222 std::optional<logging::Level> GetLocalLogLevel() const;
223
224 /// Set link - a request ID within a service. Can be called only once.
225 ///
226 /// Propagates within a single service, but not from client to server. A new
227 /// link is generated for the "root" request handling task.
228 void SetLink(std::string_view link);
229
230 /// Set parent link - request ID of the upstream service. Can only be called once.
231 ///
232 /// Propagates within a single service.
233 void SetParentLink(std::string_view parent_link);
234
235 /// Get link - a request ID within the service.
236 ///
237 /// Propagates within a single service, but not from client to server. A new
238 /// link is generated for the "root" request handling task.
239 std::string_view GetLink() const;
240
241 /// Set parent link - request ID of the upstream service. Can only be called once.
242 ///
243 /// Propagates within a single service.
244 std::string_view GetParentLink() const;
245
246 /// An ID of the request that does not change from service to service.
247 ///
248 /// Propagates both to sub-spans within a single service, and from client
249 /// to server
250 std::string_view GetTraceId() const;
251
252 /// Identifies a specific span. It does not propagate.
253 std::string_view GetSpanId() const;
254
255 /// Span ID of the nearest loggable parent span, or empty string if none exists.
256 std::string_view GetParentId() const;
257
258 /// Span ID of the nearest loggable span within the span chain, including the current span.
259 /// If the current span and all parent spans will not be logged, returns `std::nullopt`.
260 std::optional<std::string_view> GetSpanIdForChildLogs() const;
261
262 /// Get name the Span was created with
263 std::string_view GetName() const;
264
265 /// @returns true if this span would be logged with the current local and
266 /// global log levels to the default logger.
267 bool ShouldLogDefault() const noexcept;
268
269 /// Detach the Span from current engine::Task so it is not
270 /// returned by CurrentSpan() any more.
272
273 /// Attach the Span to current engine::Task so it is returned
274 /// by CurrentSpan().
276
277 std::chrono::system_clock::time_point GetStartSystemTime() const;
278
279 /// @cond
280 // For internal use only.
281 void AddTags(const logging::LogExtra&, utils::impl::InternalTag);
282
283 // For internal use only.
284 impl::TimeStorage& GetTimeStorage(utils::impl::InternalTag);
285
286 // For internal use only.
287 void LogTo(utils::impl::InternalTag, logging::impl::TagWriter writer) const;
288 /// @endcond
289
290private:
291 struct OptionalDeleter {
292 void operator()(Impl*) const noexcept;
293
294 static OptionalDeleter ShouldDelete() noexcept;
295
296 static OptionalDeleter DoNotDelete() noexcept;
297
298 private:
299 explicit OptionalDeleter(bool do_delete) : do_delete(do_delete) {}
300
301 const bool do_delete;
302 };
303
304 friend class SpanBuilder;
305 friend class TagScope;
306 friend class InPlaceSpan;
307
308 explicit Span(std::unique_ptr<Impl, OptionalDeleter>&& pimpl);
309
310 std::string_view GetTag(std::string_view tag) const;
311
312 std::unique_ptr<Impl, OptionalDeleter> pimpl_;
313};
314
315namespace impl {
316
317class DetachLocalSpansScope final {
318public:
319 DetachLocalSpansScope() noexcept;
320 ~DetachLocalSpansScope();
321
322 DetachLocalSpansScope(DetachLocalSpansScope&&) = delete;
323 DetachLocalSpansScope& operator=(DetachLocalSpansScope&&) = delete;
324
325private:
326 struct Impl;
327 utils::FastPimpl<Impl, 16, 8> impl_;
328};
329
330struct LogSpanAsLastNoCurrent final {
331 const Span& span;
332};
333
334logging::LogHelper& operator<<(logging::LogHelper& lh, LogSpanAsLastNoCurrent span);
335
336} // namespace impl
337
338} // namespace tracing
339
340USERVER_NAMESPACE_END