Search code examples
postsharp

Log additional info OnEntry or OnSuccess


is there a way to log username or user id (or some additional data) together with parameters on OnEntry/OnSuccess/OnException.

I need my log record to look like:

"... Method MethodName invoked with params [param1: value1, param2: value2 ...] by User : [username]"

Thanks.


Solution

  • The following code is taken from the Postsharp documentation site at Trace Sample with some minor modification

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