Search code examples
c#aoppostsharp

Apply a PostSharp aspect to all methods in class to Log method name


I would like to create an attribute, that I want to apply to a class. In this class, if a method was called, in the OnEntry and OnExit methodof postsharp, I want to log the exact method name like this:

"GetPartners starting..."

or

"GetPartners finished..."

or if an exception occured:

"Exception occured in GetPartners method"

Is there any solution for this?


Solution

  • There are a few options available to enable methods tracing.

    First of all, you can use an existing PostSharp Diagnostics Pattern Library and just add and configure the [Log] attribute from that library: Adding detailed tracing.

    If you want to create your own attribute, then an example is available here: "PostSharp.Samples.CustomLogging".

    Basically you need to derive from the class OnMethodBoundaryAspect and override methods OnEntry, OnExit, OnException to write your messages.

    For better performance you can prepare the corresponding messages during compile-time and reuse them at run-time in your handlers, as shown in the example:

    public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
    {
        string methodName = method.DeclaringType.FullName + "." + method.Name;
        this.enteringMessage = "Entering " + methodName;
        this.exitingMessage = "Exiting " + methodName;
    }