Skip to content

.NET Core 获取 SkyWalking 当前的 TraceId

🏷️ SkyWalking .NET Core

注意

2019-6-26 追记:新版本中已经找不到 GlobalTraceId 属性了。

  1. 安装 SkyWalking.Agent.AspNetCore

    当前最新版本是 0.6.0。

    batch
    Install-Package SkyWalking.Agent.AspNetCore
  2. 通过 ContextManager 中的 GlobalTraceId 获取当前的 TraceId

    csharp
    /// <summary>
    /// Trace Id
    /// </summary>
    public string TraceId { get; set; } = SkyWalking.Context.ContextManager.GlobalTraceId;
  3. GlobalTraceId 属性的源码

    csharp
    namespace SkyWalking.Context
    {
        /// <summary>
        /// Context manager controls the whole context of tracing. Since .NET server application runs as same as Java,
        /// We also provide the CONTEXT propagation based on ThreadLocal mechanism.
        /// Meaning, each segment also related to singe thread.
        /// </summary>
        public class ContextManager : ITracingContextListener, IIgnoreTracerContextListener
        {
            static ContextManager()
            {
                var manager = new ContextManager();
                TracingContext.ListenerManager.Add(manager);
                IgnoredTracerContext.ListenerManager.Add(manager);
            }
    
            private static readonly AsyncLocal<ITracerContext> _context = new AsyncLocal<ITracerContext>();
    
            public static string GlobalTraceId
            {
                get
                {
                    if (_context.Value != null)
                    {
                        return _context.Value.GetReadableGlobalTraceId();
                    }
    
                    return "N/A";
                }
            }
        }
    }