SkyWalking 6.1 & SkyApm.Agent.AspNetCore

.NET Core 项目使用的是 SkyWalking.Agent.AspNetCore -Version 0.6.0 包来加载 SkyWalking 探针,但是在多线程中跟踪时会发生如下异常:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
    at SkyWalking.Diagnostics.SqlClient.SqlClientTracingDiagnosticProcessor.BeforeExecuteCommand(SqlCommand sqlCommand)
如何设置 SkyWalking 中 Trace 记录的保留时间(过期时间)?

之前配置 SkyWalking 时没有注意,导致请求的详细信息在记录不久之后(2 个小时不到)就查不到了。

查到在官方文档 TTL 中的如下描述:

.NET Core 获取 SkyWalking 当前的 TraceId

注意

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

  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";
                }
            }
        }
    }