2016-07-19 4 views
2

공통 추적 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는 내 추적 ID입니다. 그러나 모든 메소드 호출마다 다른 추적 ID가 생성됩니다. 나는 그것을 독특하게 유지하고 싶다. 이것을 달성하는 방법? (참고 : method1, method2를 다른 클라이언트에서 호출)

답변

1

클래스 이름 및/또는 사용자의 .NET < = 4.0에 대한 정보가 필요하면 StackFrame을 사용하십시오. StackFrame을 사용하면 약간의 오버 헤드가 발생합니다. 클래스 이름을 가져올 필요가 없으며 .NET> = 4.5를 사용하면 여기에 solution이 있습니다. 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")) { } 
     } 
    } 
} 
+0

단일 범위를 사용할 수 있습니까? – Karthikeyan

+0

@Karthikeyan, 당신은 무엇을 의미합니까? –

+0

모든 방법에서 사용하는 것은 좋지 않습니다. 그래서 그것을 피하기 위해 어떤 방법이 있습니까? – Karthikeyan