File: Log\TraceEventSink.cs
Web Access
Project: Microsoft.CodeAnalysis.Workspaces.csproj (Microsoft.CodeAnalysis.Workspaces)
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.ErrorReporting;

namespace Microsoft.CodeAnalysis.Internal.Log;

/// <summary>
/// Implementation of <see cref="IEventSink"/> that produces timing debug output. Opt-in: registered by
/// the Performance Loggers options page while enabled, and unregistered when not.
/// </summary>
internal sealed class TraceEventSink(Func<FunctionId, bool> isEnabledPredicate) : IEventSink
{
    public bool IsEnabled(FunctionId functionId)
        => isEnabledPredicate(functionId);

    public void ReportFault(Exception exception, ErrorSeverity severity, bool forceDump)
    {
        if (IsEnabled(FunctionId.NonFatalWatson))
            Log(FunctionId.NonFatalWatson, exception.ToString());
    }

    public void Log(FunctionId functionId, LogMessage logMessage)
        => Log(functionId, logMessage.GetMessage());

    public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken)
        => Trace.WriteLine(string.Format("[{0}] Start({1}) : {2} - {3}", Environment.CurrentManagedThreadId, uniquePairId, functionId.ToString(), logMessage.GetMessage()));

    public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken)
    {
        var functionString = functionId.ToString() + (cancellationToken.IsCancellationRequested ? " Canceled" : string.Empty);
        Trace.WriteLine(string.Format("[{0}] End({1}) : [{2}ms] {3}", Environment.CurrentManagedThreadId, uniquePairId, delta, functionString));
    }

    [Conditional("TRACE")]
    private static void Log(FunctionId functionId, string message)
        => Trace.WriteLine(string.Format("[{0}] {1} - {2}", Environment.CurrentManagedThreadId, functionId.ToString(), message));
}