Skip to content

Activity should have AddExceptionMethod #53641

Closed

Description

@DR9885

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.

Activity

  1. ghost added
    untriaged
    on Jun 2, 2021
  2. added and removed
    untriaged
    on Jun 2, 2021
  3. added this to the Future milestone on Jun 2, 2021
  4. tarekgh commented on Jun 2, 2021

    @tarekgh
    Member

    Why can't use Activity.SetCustomProperty?

    Something like:

    activity.SetCustomProperty("exception", exceptionObject);

    In general, for error reporting we followed up OpenTelemetry specs and provided Activity.SetStatus. So, you can also do:

    activity.SetStatus(ActivityStatusCode.Error, exceptionObject.ToString());

    I don't think adding a method for exception will be desirable for most scenarios as wouldn't be portable.

    CC @noahfalk

  5. noahfalk commented on Jun 2, 2021

    @noahfalk
    Member

    There is a semantic convention for exceptions but it is currently marked experimental. I do not recommend we codify it into the BCL until it is more stable, but once it was stable AddException() seems like a useful API.

  6. DR9885 commented on Jun 9, 2021

    @DR9885
    Author

    Theres also a few tags listed on microsoft docs:

    otel.status_code
    otel.status_description
    

    https://docs.microsoft.com/en-us/dotnet/core/diagnostics/distributed-tracing-instrumentation-walkthroughs#optional-add-status

    ... However ... I Just realized this is done by SetStatus, so maybe redundant to an earlier comment

    Based on all comments though, It might be better if SetStatus did all of this:

      public static Activity SetStatus(this Activity activity, Status status, Exception ex = null)
            {
                return activity?.SetTag("event", "error")
                    .SetTag("otel.status_code", status.ToString())
                    .SetTag("otel.status_description", ex.Message)
                    .SetTag("error", "true")
                    .SetTag("error.kind", ex.GetType().Name)
                    .SetTag("error.message", ex.Message)
                    .SetTag("error.stack", ex.StackTrace);
            }
    
  7. CodeBlanch commented on Nov 12, 2021

    @CodeBlanch
    Contributor

    @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

  8. cijothomas commented on Nov 12, 2021

    @cijothomas
    Contributor

    Related issue : open-telemetry/opentelemetry-dotnet-contrib#1794
    (There are privacy concerns about storing stack as activity event)

  9. 49 remaining items

  10. added
    blocking
    api-ready-for-review
    on May 24, 2024
  11. terrajobst commented on May 28, 2024

    @terrajobst
    Contributor

    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; }
    }
  12. added
    api-approved
    and removed
    api-ready-for-review
    on May 28, 2024
  13. tarekgh commented on May 30, 2024

    @tarekgh
    Member

    @terrajobst @bartonjs, as we have decided to use the method name AddException instead of RecordException, and considering the pattern of other methods in the Activity class, the Add methods always return the Activity instead of void. I will follow this pattern and make AddException return Activity instead of void. Please let me know if you have any concerns about this. Thanks!

    public Activity AddTag(string key, string? value) => AddTag(key, (object?)value);



    public Activity AddBaggage(string key, string? value)

  14. terrajobst commented on May 31, 2024

    @terrajobst
    Contributor

    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; }
    }
  15. added
    in-pr
    on May 31, 2024
  16. tarekgh commented on Jun 3, 2024

    @tarekgh
    Member

    @terrajobst @bartonjs sorry to ping again, there was a suggestion to mark the tags parameter with in keyword to avoid copying the TagList struct. what do you think?

    public Activity AddException(Exception exception, in TagList tags = default, DateTimeOffset timestamp = default);

    @CodeBlanch

  17. bartonjs commented on Jun 3, 2024

    @bartonjs
    Member

    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.

  18. tarekgh commented on Jun 3, 2024

    @tarekgh
    Member

    Thanks @bartonjs!

    I'll go ahead and apply that if @terrajobst has no objection.

  19. tarekgh commented on Jun 3, 2024

    @tarekgh
    Member

    I created the PR #103009 to update the tags parameter modifier.

  20. KalleOlaviNiemitalo commented on Jun 4, 2024

    @KalleOlaviNiemitalo

    It seems ActivitySource can call the ExceptionRecorder delegate multiple times with the same arguments, if another thread adds or removes listeners in parallel with Activity.AddException. This is more surprising for ExceptionRecorder, which is designed to have side effects on the TagList, than for ShouldListenTo. It will probably be OK but it should preferably be documented.

  21. locked and limited conversation to collaborators on Jul 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedarea-System.Diagnostics.Activityblockingfeature-requestin-pr

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions