2016-09-05 2 views
0

PostSharp LogAttribute 및 log4net을 사용하여 호출 된 모든 메소드에 대한 추적을 생성합니다.PostSharp 로그 메시지의 접두어 삭제

출력은 잘하지만 각 줄에 반복 라벨 Entering: 제거하려면 : 그것은 PostSharp 팀은 메시지 형식 정의를 추가하지 않을 것이 분명

17:48:34,694 [Main  ]  Entering: LoginPopUp.LoginClick() 
17:48:34,695 [Main  ]   Entering: UserRepository.GetUser() 
17:48:34,695 [Main  ]   Entering: UserRepository.IsAdmin() 
17:48:34,696 [Main  ]    Entering: SecurityManager.Encrypt() 

this answer에서.

또한 사용자 정의 TraceAttribute derived from OnMethodBoundaryAspect 의 예가 있으며 사용자 정의가 더 유연한 것으로 보입니다. 그러나 문제는이 경우 중첩 수준을 나타내는 들여 쓰기를 잃게된다는 것입니다 (모든 줄에 입력 단어를 갖는 것보다 나에게 더 중요합니다).

가장 좋은 해결책은 LogAttribute를 확장하여 접두어를 사용자 정의하는 것이지만 가능한지 여부를 모르겠습니다.

접두어 Entering:은 어떻게 삭제합니까? 피터 기반으로

작동 코드는

static readonly Dictionary<Thread, int> DepthDictionary = new Dictionary<Thread, int>(); 

    // Invoked at runtime before that target method is invoked. 
    public override void OnEntry(MethodExecutionArgs args) 
    { 
     int depth; 
     DepthDictionary.TryGetValue(Thread.CurrentThread, out depth); 
     Trace.WriteLine(getIndent(depth) + this.enteringMessage, this.category); 
     DepthDictionary[Thread.CurrentThread] = depth+1; 
    } 

    // Invoked at runtime after the target method is invoked (in a finally block). 
    public override void OnExit(MethodExecutionArgs args) 
    { 
     var depth = --DepthDictionary[Thread.CurrentThread]; 
     Trace.WriteLine(getIndent(depth) + this.exitingMessage, this.category); 
    } 

    private string getIndent(int depth) 
    { 
     string result = ""; 
     for (int i = 0; i < depth; i++) result += " "; 
     return result; 
    } 

답변

1

솔루션은 그냥 답하라에게 당신의 자신을 추가 할 수있는 멀티 스레딩되지 않습니다 :

// Invoked only once at runtime from the static constructor of type declaring the target method. 
    public override void RuntimeInitialize(MethodBase method) 
    { 
     string methodName = method.DeclaringType.FullName + method.Name; 
     this.enteringMessage = methodName; 
     this.exitingMessage = methodName; 
    } 

    static int depth = 0; 

    // Invoked at runtime before that target method is invoked. 
    public override void OnEntry(MethodExecutionArgs args) 
    { 
     Trace.WriteLine(getIndent()+this.enteringMessage, this.category); 
     depth++; 
    } 

    // Invoked at runtime after the target method is invoked (in a finally block). 
    public override void OnExit(MethodExecutionArgs args) 
    { 
     depth--; 
     Trace.WriteLine(getIndent()+this.exitingMessage, this.category); 
    } 

    private string getIndent(){ 
     string result = ""; 
     for (int i = 0; i < depth;i++) result += " "; 
     return result; 
    } 

example-trace

+0

좋아 보인다지만 작동하지 않는가. OnEntry에서 심도 변수는 항상 0입니다. –

+0

정적으로 만듭니다. 나는 코드 – Peter

+0

을 바꿀 것이다. 어쩌면 멀티 스레딩 프로그램에서 어떻게 작동하게 할 수 있습니까? –

0

그것이 log4net 사용자 정의 PatternLayoutConverter에서하려면 string.replace을 사용하지만, 최고의 솔루션이 될 것 같지 않습니다 삭제할 ​​수의 응답.

사용자 지정 TraceAttribute를 기반으로하는 솔루션을 얻는 것이 좋을 것입니다.