Skip to content

Public setter for System.Diagnostics.Activity.Current #25936

@lmolkova

Description

@lmolkova

Motivation

Activity represents a context for distributed operation tracing.
It is created when an operation (e.g. Http request) starts and flows with async calls within a process.

Activity.Current is AsyncLocal static variable that any logger/tracing system can use to stamp logs and telemetry with 'correlation ids'.

Activity.Current could be set via calling Activity.Start or Activity.Stop which are enough as long as managed asyncronous flow is guaranteed which is not always the case.

Typical example is ASP.NET application hosed with IIS where hop from managed to native thread chould happen at any step in the request execution pipeline. ASP.NET propagates HttpContext through such hops.

With current API, it is not possible to assign Current Activity 'back' to what it was before the hop.

Proposed API

Add public setter for Activity.Current.

Usage

Such method could be called from the certain points in the request execution pipeline:

public void RestoreActivityIfNeeded(HttpContext context)
{
    if (Activity.Current == null)
    {
        var storedActivity = (Activity)context.Items["AspNetActivityKey"];
        if (storedActivity != null)
        {
            Activity.Current = storedActivity; //!!!
        }
    }
}

Details

  • stopped/not started Activities should not be allowed as it makes Current stack invalid. E.g.
    Activity.Current = stopped;
    Activity.Current.Stop();  // Noop, never changes Current to Parent
    Activity.Current = notStarted;
    notStarted.Stop() // Noop, never changes Current to Parent
  • arguably, Activity.Current = null is valid. E.g. fork a background task with no context without stopping all stack
Activity a = new Activity("incoming request").Start();

Task.Run(() => {
    Activity.Current = null;
    // start long-running task
});

// continune execution in the same context

Pull Request

Proposed changes: dotnet/corefx#29208

cc @vancem

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions