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