.NET Core 获取 SkyWalking 当前的 TraceId
注意
2019-6-26 追记:新版本中已经找不到 GlobalTraceId
属性了。
安装
SkyWalking.Agent.AspNetCore
包当前最新版本是 0.6.0。
batchInstall-Package SkyWalking.Agent.AspNetCore
1通过
ContextManager
中的GlobalTraceId
获取当前的TraceId
csharp/// <summary> /// Trace Id /// </summary> public string TraceId { get; set; } = SkyWalking.Context.ContextManager.GlobalTraceId;
1
2
3
4- 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"; } } } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32