如何使用公共跟踪标识?

How to use common trace id?

我想使用通用跟踪 ID。我正在使用以下代码。

 public void method1(){
      using (new Tracer(Guid.NewGuid().ToString()))
        {
            //my code
        }
  }
  public void method2(){
      using (new Tracer(Guid.NewGuid().ToString()))
        {
            //my code
        }
  } 

这里的guid是我的trace id。但是为每个方法调用生成不同的跟踪 ID。我想保持它的独特性。如何实现这一目标? (注意:我从不同的客户端调用方法 1、方法 2)

如果您需要获取有关 class 名称 and/or 您的 .NET <= 4.0 的信息,请使用 StackFrame. You'll get some overhead with StackFrame. If you don't need to get the name of class and you use .NET >= 4.5, here is solution. It uses Caller Information。 :

namespace Tracer
{
    using System;
    using System.Runtime.CompilerServices;
    sealed class CallerInfoTracer : IDisposable
    {
        private readonly string _message;
        private readonly string _memberName;
        private readonly string _sourceFilePath;
        private readonly int _lineNumber;

        private bool _disposed;

        public CallerInfoTracer(string message, [CallerMemberName] string memberName = "",
            [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int lineNumber = 0)
        {
            _message = message;
            _memberName = memberName;
            _sourceFilePath = sourceFilePath;
            _lineNumber = lineNumber;
        }
        public void Dispose()
        {
            if (_disposed) return;

            Console.WriteLine("Message: {0}", _message);
            Console.WriteLine("MemberName: {0}", _memberName);
            Console.WriteLine("SourceFilePath: {0}", _sourceFilePath);
            Console.WriteLine("LineNumber: {0}", _lineNumber);
            _disposed = true;
        }
    }
    public class Program
    {
        public static void Main(string[] args)
        {
            Method1();
            Method2();
        }
        public static void Method1()
        {
            using (var tracer = new CallerInfoTracer("Desc1")) { }
        }
        public static void Method2()
        {
            using (var tracer = new CallerInfoTracer("Desc2")) { }
        }
    }
}