Concware Concware - 1 year ago 105
C# Question

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

methodof postsharp, I want to log the exact method name like this:

"GetPartners starting..."


"GetPartners finished..."

or if an exception occured:

"Exception occured in GetPartners method"

Is there any solution for this?

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download