Skip to content

Instantly share code, notes, and snippets.

@arakis
Last active July 23, 2021 16:25
Show Gist options
  • Save arakis/6063fc4c263ef797651c7066d6a47870 to your computer and use it in GitHub Desktop.
Save arakis/6063fc4c263ef797651c7066d6a47870 to your computer and use it in GitHub Desktop.
Start new Root Activity/Span, when Activity.Current is already present
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);
}
}
}
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