记录其他信息OnEntry或OnSuccess

时间:2014-04-15 13:39:49

标签: postsharp

有没有办法将用户名或用户ID(或其他一些数据)与OnEntry / OnSuccess / OnException上的参数一起记录。

我需要我的日志记录:

“...方法MethodName用params调用[param1:value1,param2:value2 ...]用户:[username]”

感谢。

1 个答案:

答案 0 :(得分:2)

以下代码取自Trace Sample的Postsharp文档网站,并进行了一些小修改

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);
}