Last active
July 23, 2021 16:25
-
-
Save arakis/6063fc4c263ef797651c7066d6a47870 to your computer and use it in GitHub Desktop.
Start new Root Activity/Span, when Activity.Current is already present
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Collections.Generic; | |
// Author: https://github.com/arakis | |
// Inspired by https://github.com/open-telemetry/opentelemetry-dotnet/issues/984 | |
// This is an usable implementation for the workaround in the above issue | |
namespace StartRootActivitySample | |
{ | |
public static class ActivitySourceExtensions | |
{ | |
public static RootActivity StartRootActivity(this ActivitySource source, | |
string name, | |
ActivityKind kind = ActivityKind.Internal, | |
IEnumerable<KeyValuePair<string, object?>>? tags = null) | |
{ | |
var parent = Activity.Current; | |
Activity.Current = null; | |
var next = source.StartActivity(name, kind, | |
parentContext: default, | |
tags: tags, | |
links: new[] { new ActivityLink(parent.Context) }); | |
return new RootActivity(next, parent); | |
} | |
} | |
public class RootActivity : IDisposable | |
{ | |
public Activity Activity { get; } | |
public Activity ParentActivity { get; } | |
public RootActivity(Activity activity, Activity parentActivity) | |
{ | |
Activity = activity; | |
ParentActivity = parentActivity; | |
} | |
private bool disposedValue; | |
protected virtual void Dispose(bool disposing) | |
{ | |
if (!disposedValue) | |
{ | |
if (disposing) | |
{ | |
Activity.Dispose(); | |
Activity.Current = ParentActivity; | |
} | |
disposedValue = true; | |
} | |
} | |
public void Dispose() | |
{ | |
Dispose(disposing: true); | |
GC.SuppressFinalize(this); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using (var root = MyActivitySource.StartRootActivity("new-root")) | |
{ | |
using (var child = MyActivitySource.StartActivity("in new root")) | |
{ | |
Log.Error("in new root"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment