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;
21
22/// @brief Measures the execution time of the current code block, links it with
23/// the parent tracing::Spans and stores that info in the log.
24///
25/// Logging of spans can be controled at runtime via @ref USERVER_NO_LOG_SPANS.
26///
27/// See @ref scripts/docs/en/userver/logging.md for usage examples and more
28/// descriptions.
29///
30/// @warning Shall be created only as a local variable. Do not use it as a
31/// class member!
32class Span final {
33public:
34 class Impl;
35
36 explicit Span(
37 TracerPtr tracer,
38 std::string name,
39 const Span* parent,
40 ReferenceType reference_type,
41 logging::Level log_level = logging::Level::kInfo,
42 utils::impl::SourceLocation source_location = utils::impl::SourceLocation::Current()
43 );
44
45 /// Use default tracer and implicit coro local storage for parent
46 /// identification, takes TraceID from the parent.
47 ///
48 /// For extremely rare cases where a new Trace ID is required use
49 /// tracing::Span::MakeSpan().
50 explicit Span(
51 std::string name,
52 ReferenceType reference_type = ReferenceType::kChild,
53 logging::Level log_level = logging::Level::kInfo,
54 utils::impl::SourceLocation source_location = utils::impl::SourceLocation::Current()
55 );
56
57 /// @cond
58 // For internal use only
59 explicit Span(Span::Impl& impl);
60 /// @endcond
61
62 Span(Span&& other) noexcept;
63
64 ~Span();
65
66 Span& operator=(const Span&) = delete;
67
68 Span& operator=(Span&&) = delete;
69
70 /// @brief Returns the Span of the current task.
71 ///
72 /// Should not be called in non-coroutine
73 /// context. Should not be called from a task with no alive Span.
74 ///
75 /// Rule of thumb: it is safe to call it from a task created by
76 /// utils::Async/utils::CriticalAsync/utils::PeriodicTask. If current task was
77 /// created with an explicit engine::impl::*Async(), you have to create a Span
78 /// beforehand.
79 static Span& CurrentSpan();
80
81 /// @brief Returns nullptr if called in non-coroutine context or from a task
82 /// with no alive Span; otherwise returns the Span of the current task.
83 static Span* CurrentSpanUnchecked();
84
85 /// Factory function for extremely rare cases of creating a Span with custom
86 /// IDs; prefer Span constructor instead.
87 ///
88 /// @return A new Span attached to current Span (if any) but with a new
89 /// Trace ID.
90 /// @param name Name of a new Span
91 /// @param trace_id New Trace ID; if empty then the Trace ID is autogenerated
92 /// @param parent_span_id Id of the parent Span, could be empty.
93 static Span MakeSpan(std::string name, std::string_view trace_id, std::string_view parent_span_id);
94
95 /// Factory function for extremely rare cases of creating a Span with custom
96 /// IDs; prefer Span constructor instead.
97 ///
98 /// @return A new Span attached to current Span (if any), sets `link`.
99 /// @param name Name of a new Span
100 /// @param trace_id New Trace ID; if empty then the Trace ID is autogenerated
101 /// @param parent_span_id Id of the parent Span, could be empty.
102 /// @param link The new link
103 static Span
104 MakeSpan(std::string name, std::string_view trace_id, std::string_view parent_span_id, std::string link);
105
106 /// Factory function for rare cases of creating a root Span that starts
107 /// the trace_id chain, ignoring `CurrentSpan`, if any. Useful
108 /// in background jobs, periodics, distlock tasks, cron tasks, etc.
109 /// The result of such jobs is not directly requested by anything.
110 ///
111 /// @return A new Span that is the root of a new Span hierarchy.
112 /// @param name Name of a new Span
113 /// @param log_level Log level for the span's own log record
114 static Span MakeRootSpan(std::string name, logging::Level log_level = logging::Level::kInfo);
115
116 /// Create a child which can be used independently from the parent.
117 ///
118 /// The child shares no state with its parent. If you need to run code in
119 /// parallel, create a child span and use the child in a separate task.
120 Span CreateChild(std::string name) const;
121
122 Span CreateFollower(std::string name) const;
123
124 /// @brief Creates a tracing::ScopeTime attached to the span.
126
127 /// @brief Creates a tracing::ScopeTime attached to the Span and starts
128 /// measuring execution time.
129 /// Tag `{scope_name}_time` with elapsed time is added to result span.
130 ///
131 /// @note `name` parameter is expected to satisfy snake case.
132 /// Otherwise, it is converted to snake case.
133 ScopeTime CreateScopeTime(std::string name);
134
135 /// Returns total time elapsed for a certain scope of this span.
136 /// If there is no record for the scope, returns 0.
137 ScopeTime::Duration GetTotalDuration(const std::string& scope_name) const;
138
139 /// Returns total time elapsed for a certain scope of this span.
140 /// If there is no record for the scope, returns 0.
141 ///
142 /// Prefer using Span::GetTotalDuration()
143 ScopeTime::DurationMillis GetTotalElapsedTime(const std::string& scope_name) const;
144
145 /// Add a tag that is used on each logging in this Span and all
146 /// future children.
147 void AddTag(std::string key, logging::LogExtra::Value value);
148
149 /// Add a tag that is used on each logging in this Span and all
150 /// future children. It will not be possible to change its value.
151 void AddTagFrozen(std::string key, logging::LogExtra::Value value);
152
153 /// Add a tag that is local to the Span (IOW, it is not propagated to
154 /// future children) and logged only once in the destructor of the Span.
155 void AddNonInheritableTag(std::string key, logging::LogExtra::Value value);
156
157 /// @overload AddNonInheritableTag
158 void AddNonInheritableTags(const logging::LogExtra&);
159
160 /// @brief Sets level for tags logging
161 void SetLogLevel(logging::Level log_level);
162
163 /// @brief Returns level for tags logging
165
166 /// @brief Sets the local log level that disables logging of this span if
167 /// the local log level set and greater than the main log level of the Span.
168 void SetLocalLogLevel(std::optional<logging::Level> log_level);
169
170 /// @brief Returns the local log level that disables logging of this span if
171 /// it is set and greater than the main log level of the Span.
172 std::optional<logging::Level> GetLocalLogLevel() const;
173
174 /// Set link - a request ID within a service. Can be called only once.
175 ///
176 /// Propagates within a single service, but not from client to server. A new
177 /// link is generated for the "root" request handling task
178 void SetLink(std::string link);
179
180 /// Set parent_link - an ID . Can be called only once.
181 void SetParentLink(std::string parent_link);
182
183 /// Get link - a request ID within the service.
184 ///
185 /// Propagates within a single service, but not from client to server. A new
186 /// link is generated for the "root" request handling task
187 std::string GetLink() const;
188
189 std::string GetParentLink() const;
190
191 /// An ID of the request that does not change from service to service.
192 ///
193 /// Propagates both to sub-spans within a single service, and from client
194 /// to server
195 const std::string& GetTraceId() const;
196
197 /// Identifies a specific span. It does not propagate
198 const std::string& GetSpanId() const;
199 const std::string& GetParentId() const;
200
201 /// @returns true if this span would be logged with the current local and
202 /// global log levels to the default logger.
203 bool ShouldLogDefault() const noexcept;
204
205 /// Detach the Span from current engine::Task so it is not
206 /// returned by CurrentSpan() any more.
208
209 /// Attach the Span to current engine::Task so it is returned
210 /// by CurrentSpan().
212
213 std::chrono::system_clock::time_point GetStartSystemTime() const;
214
215 /// @cond
216 // For internal use only.
217 void AddTags(const logging::LogExtra&, utils::impl::InternalTag);
218
219 // For internal use only.
220 impl::TimeStorage& GetTimeStorage(utils::impl::InternalTag);
221
222 // For internal use only.
223 void LogTo(logging::impl::TagWriter writer) const&;
224 /// @endcond
225
226private:
227 struct OptionalDeleter {
228 void operator()(Impl*) const noexcept;
229
230 static OptionalDeleter ShouldDelete() noexcept;
231
232 static OptionalDeleter DoNotDelete() noexcept;
233
234 private:
235 explicit OptionalDeleter(bool do_delete) : do_delete(do_delete) {}
236
237 const bool do_delete;
238 };
239
240 friend class SpanBuilder;
241 friend class TagScope;
242
243 explicit Span(std::unique_ptr<Impl, OptionalDeleter>&& pimpl);
244
245 std::string GetTag(std::string_view tag) const;
246
247 std::unique_ptr<Impl, OptionalDeleter> pimpl_;
248};
249
250namespace impl {
251
252class DetachLocalSpansScope final {
253public:
254 DetachLocalSpansScope() noexcept;
255 ~DetachLocalSpansScope();
256
257 DetachLocalSpansScope(DetachLocalSpansScope&&) = delete;
258 DetachLocalSpansScope& operator=(DetachLocalSpansScope&&) = delete;
259
260private:
261 struct Impl;
262 utils::FastPimpl<Impl, 16, 8> impl_;
263};
264
265struct LogSpanAsLastNoCurrent final {
266 const Span& span;
267};
268
269logging::LogHelper& operator<<(logging::LogHelper& lh, LogSpanAsLastNoCurrent span);
270
271} // namespace impl
272
273} // namespace tracing
274
275USERVER_NAMESPACE_END