This repository was archived by the owner on Jul 31, 2023. It is now read-only.
File tree Expand file tree Collapse file tree 3 files changed +21
-4
lines changed
Expand file tree Collapse file tree 3 files changed +21
-4
lines changed Original file line number Diff line number Diff line change @@ -26,14 +26,15 @@ using ::opencensus::trace::Span;
2626namespace opencensus {
2727namespace trace {
2828
29- WithSpan::WithSpan (const Span& span, bool cond)
29+ WithSpan::WithSpan (const Span& span, bool cond, bool end_span )
3030 : swapped_span_(span)
3131#ifndef NDEBUG
3232 ,
3333 original_context_ (Context::InternalMutableCurrent())
3434#endif
3535 ,
36- cond_ (cond) {
36+ cond_ (cond),
37+ end_span_(end_span) {
3738 ConditionalSwap ();
3839}
3940
@@ -43,6 +44,9 @@ WithSpan::~WithSpan() {
4344 " WithSpan must be destructed on the same thread as it was "
4445 " constructed." );
4546#endif
47+ if (cond_ && end_span_) {
48+ Context::InternalMutableCurrent ()->span_ .End ();
49+ }
4650 ConditionalSwap ();
4751}
4852
Original file line number Diff line number Diff line change @@ -107,6 +107,17 @@ TEST(WithSpanTest, DisabledViaConditional) {
107107 span1.End ();
108108}
109109
110+ TEST (WithSpanTest, EndSpan) {
111+ auto span = opencensus::trace::Span::StartSpan (" MySpan" );
112+ ExpectNoSpan ();
113+ {
114+ opencensus::trace::WithSpan ws (span, /* cond=*/ true , /* end_span=*/ true );
115+ EXPECT_EQ (span.context (), ContextTestPeer::CurrentCtx ());
116+ }
117+ ExpectNoSpan ();
118+ // TODO: Check End() was called.
119+ }
120+
110121#ifndef NDEBUG
111122TEST (WithSpanDeathTest, DestructorOnWrongThread) {
112123 auto span = opencensus::trace::Span::StartSpan (" MySpan" );
Original file line number Diff line number Diff line change @@ -23,7 +23,8 @@ namespace trace {
2323
2424// WithSpan is a scoped object that sets the current Span to the given one,
2525// until the WithSpan object is destroyed. If the condition is false, it doesn't
26- // do anything.
26+ // do anything. If the condition is true and end_span is true, it calls End() on
27+ // the Span when it falls out of scope.
2728//
2829// Because WithSpan changes the current (thread local) context, NEVER allocate a
2930// WithSpan in one thread and deallocate in another. A simple way to ensure this
@@ -36,7 +37,7 @@ namespace trace {
3637// }
3738class WithSpan {
3839 public:
39- explicit WithSpan (const Span& span, bool cond = true );
40+ explicit WithSpan (const Span& span, bool cond = true , bool end_span = false );
4041 ~WithSpan ();
4142
4243 // No Span&& constructor because it encourages "consuming" the Span with a
@@ -57,6 +58,7 @@ class WithSpan {
5758 const ::opencensus::context::Context* original_context_;
5859#endif
5960 const bool cond_;
61+ const bool end_span_;
6062};
6163
6264} // namespace trace
You can’t perform that action at this time.
0 commit comments