2014-04-15 2 views
1

에는 OnEntry/OnSuccess/OnException의 매개 변수와 함께 사용자 이름 또는 사용자 ID (또는 일부 추가 데이터)를 기록하는 방법이 있습니다.추가 정보 기록 OnEntry/OnSuccess

"... 방법 methodName로는 PARAMS 호출 사용자에 의해 [PARAM1 : 값 2 ... : 값 1, PARAM2] : [사용자 이름]"

감사

나는 같이 내 로그 기록이 필요합니다 .

+0

으로 Trace Sample에서 Postsharp 문서 사이트에서 가져온 것입니다 ... http://stackoverflow.com/questions/12641871/using- postsharp-with-traceattribute-for-logging-with-httpcontexts-sessionid? rq = 1 – user1376929

답변

2

다음 코드는 사실이 내가 필요로 무엇을 약간 수정

using System; 
using System.Diagnostics; 
using System.Reflection; 
using PostSharp.Aspects; 

namespace Samples 
{ 
    [Serializable] 
    public sealed class TraceAttribute : OnMethodBoundaryAspect 
    { 
     // This field is initialized and serialized at build time, then deserialized at runtime. 
     private readonly string category; 

     // These fields are initialized at runtime. They do not need to be serialized. 
     [NonSerialized] private string enteringMessage; 
     [NonSerialized] private string exitingMessage; 

     // Default constructor, invoked at build time. 
     public TraceAttribute() 
     { 
     } 

     // Constructor specifying the tracing category, invoked at build time. 
     public TraceAttribute(string category) 
     { 
      this.category = category; 
     } 


     // 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 = "Entering " + methodName; 
      this.exitingMessage = "Exiting " + methodName; 
     } 

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

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

private void DisplayArgs(MethodExecutionArgs args) 
{ 
    var parameters = args.Method.GetParameters(); 
    var arguments = args.Arguments; 
    var zipped = parameters.Zip(arguments, (f,s) => f.Name + ":" + s == null ? "null" : s.ToString()); 
    string traceLine = string.Format("invoked with params [{0}] by User:[{1}]", string.Join(",", zipped), 
    System.Security.Principal.WindowsIdentity.GetCurrent().Name); 
    System.Diagnostics.Trace.TraceInformation(traceLine); 
}