.NET Core 获取 SkyWalking 当前的 TraceId

  1. 安装 SkyWalking.Agent.AspNetCore

    当前最新版本是 0.6.0 。

    Install-Package SkyWalking.Agent.AspNetCore
    
  2. 通过 ContextManager 中的 GlobalTraceId 获取当前的 TraceId
    /// <summary>
    /// Trace Id
    /// </summary>
    public string TraceId { get; set; } = SkyWalking.Context.ContextManager.GlobalTraceId;
    
  3. GlobalTraceId 属性的源码
    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";
                }
            }
        }
    }
    

© 2018, 佳佳. 版权所有. 转载请注明出处.

发表评论

电子邮件地址不会被公开。 必填项已用*标注