runtime: Activity should have AddExceptionMethod

Edited by @tarekgh

Proposal

This proposal aims to enable the recording of exceptions during tracing operations, in accordance with the OpenTelemetry Record Exception specification

namespace System.Diagnostics;

public class Activity
{
    public void RecordException(Exception exception, TagList tags = default, DateTimeOffset timestamp = default);
}

public delegate void ExceptionRecording(Activity activity, Exception exception, ref TagList tags);

public sealed class ActivityListener : IDisposable
{
    // Will be invoked when Activity.RecordException is called.
    public ExceptionRecording? ExceptionRecording { get; set; }
}

Notes

  • RecordException will save details of the exception into an ActivityEvent entry, adhering to the guidelines of the OpenTelemetry semantic convention.
  • RecordException captures information such as the stack trace, exception type name, and exception message, but not the exception object itself. This approach is chosen because the exception might be rethrown, potentially altering the stack trace. Additionally, exception objects can be large and complex, leading to performance issues.
  • Anyone interested in accessing the actual exception object during recording can use ActivityListener.ExceptionRecording, which provides a notification that includes the exception objects along with the tags to be recorded. When listeners are enabled, the behavior of RecordException will be as follows:
    • RecordException will iterate through all non-nullable ExceptionRecording listeners one by one, passing the exception object and the input tags list provided to RecordException. Listeners can add or modify tags as necessary.
    • If multiple registered listeners modify the same tags, the changes made by the last listener will prevail and be recorded in the event.
    • After calling all listeners, RecordException adds the populated event to the Activity.Events list. If any tags specified in the OpenTelemetry semantic convention are missing, they will be added to the tag list before the event is stored.
  • RecordException will always log the event, and there will be no option to suppress its addition.

The recorded event will have the name as exception and will include the following tags:


Usage Example

    using ActivitySource aSource =  new ActivitySource("SourceActivityListener");
    
    using ActivityListener listener = new ActivityListener();
    listener.ShouldListenTo = (activitySource) => object.ReferenceEquals(aSource, activitySource);
    listener.Sample = (ref ActivityCreationOptions<ActivityContext> activityOptions) => ActivitySamplingResult.AllData;
    listener.ExceptionRecording = (activity, exception, ref tags) => { /* access the exception and the tags */  };
    ActivitySource.AddActivityListener(listener);

    using Activity activity = aSource.StartActivity("AllDataRequestedActivity");
    activity.RecordException(new Exception("Exception to be recorded"), new TagList { { "exception.escaped", "true" } }, DateTimeOffset.UtcNow );
    
    ActivityEvent exceptionEvent = activity.Events.First();

Original Proposal

Activity should have AddExceptionMethod, rather than having to set these tags everytime.

        public static Activity AddException(this Activity activity, Exception ex)
        {
            return activity?.AddTag("event", "error")
                .AddTag("error", "true")
                .AddTag("error.kind", ex.GetType().Name)
                .AddTag("error.message", ex.Message)
                .AddTag("error.stack", ex.StackTrace);
        }

This should also have constants for these strings, for performance.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 1
  • Comments: 61 (39 by maintainers)

Most upvoted comments

I have updated the proposal and added some notes at the top. Please have a look and let me know if you have any feedback before we proceed with that proposal. Thanks!

My initial thought is “using in goes against our guidelines”. But that sounds familiar for this, and looking at the ref.cs it does appear that this struct is only ever passed as ref or in; so in would be consistent here, I guess.

Returning Activity makes sense, so:

namespace System.Diagnostics;

public partial class Activity
{
    public Activity AddException(Exception exception, TagList tags = default, DateTimeOffset timestamp = default);
}

public delegate void ExceptionRecorder(Activity activity, Exception exception, ref TagList tags);

public partial class ActivityListener : IDisposable
{
    public ExceptionRecorder? ExceptionRecorder { get; set; }
}

Video

  • We prefer the er suffix for the delegate
  • We should use Add as the prefix as that’s consistent with other methods on Activity
  • We concluded we don’t need to make the parameters nullable
namespace System.Diagnostics;

public partial class Activity
{
    public void AddException(Exception exception, TagList tags = default, DateTimeOffset timestamp = default);
}

public delegate void ExceptionRecorder(Activity activity, Exception exception, ref TagList tags);

public partial class ActivityListener : IDisposable
{
    public ExceptionRecorder? ExceptionRecorder { get; set; }
}

This is the same direction I am thinking in. Is to store the exception object in the event. The only thing raised and not addressed is how to handle the rethrow case as the stack can change after recording it. This is what I was trying to get some feedback on how common this scenario or should we care much about it? I know there is some ideas in this issue to expose some callback in the activity listener to allow users get the notification when recording the exception.

@jamescrosswell, what kind of debug files are you using that Exception.StackTrace does not parse already?

One example of something we do with raw exceptions is to generate enhanced stack frames using Ben.Demystifier.

There are plenty of other examples but the TLDR; is that StackTrace.ToString() is insufficient. We need structured exception data to work with.

If it’s stored on the Activity that limits it to one per Activity

No, we can return AggregatedException. Or we can decide to expose the recorded exceptions as IEnumerable<Exception>.

@cijothomas the question is, do we need to support timestamps with the proposal https://github.com/dotnet/runtime/issues/53641#issuecomment-966773529?

@DR9885 Just to clarify this a bit, the OTel spec doesn’t say to add tags for an exception, it says to add an event (with tags). Here is the extension method we have in the OTel.NET library for this: https://github.com/open-telemetry/opentelemetry-dotnet/blob/4c22707a98abf356fa4224ebbc872f3bad0d72c6/src/OpenTelemetry.Api/Trace/ActivityExtensions.cs#L95

But yes it would be great to have this API on activity so that users don’t need the OpenTelemetry.Api dependency.

I was thinking the .NET API would be something simple like…

class Activity
{
   public Exception? Exception { get; set; }
}

…or…

class Activity
{
   public Exception? Exception { get; }

   public void RecordException(Exception exception) { ... }
}

And then the OpenTelemetry library (or anyone interested) could worry about what to do with it.

/cc @cijothomas