Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log method calls on targets marked with an attribute?

Tags:

c#

Is it possible to inject Loggin behaviour to the marked classes or/and methods like this:

Log("Method {0} started",GetMethodNameTroughReflection)
Call method body
Log("Method {0} Finished",GetMethodNameTroughReflection)

I want to create my own Attribute class, which will realize loging behaviour for method call.

I want to describe login behaviour in the app.config file, thoug it can be disabled by a setting in config.

How to do it right? Maybe there is created solution for tasks like this one?

like image 813
v00d00 Avatar asked Nov 09 '10 12:11

v00d00


People also ask

What is method attribute in C#?

Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection.

What is attribute in C# with example?

In C#, attributes are classes that inherit from the Attribute base class. Any class that inherits from Attribute can be used as a sort of "tag" on other pieces of code. For instance, there is an attribute called ObsoleteAttribute . This is used to signal that code is obsolete and shouldn't be used anymore.

What is a .NET attribute?

Attributes are used for adding metadata, such as compiler instruction and other information such as comments, description, methods and classes to a program. The . Net Framework provides two types of attributes: the pre-defined attributes and custom built attributes.


1 Answers

This can be done using aspect-oriented programming (AOP). Have a look at PostSharp. See the sample for tracing here:

Non-Invasive Tracing & Logging

like image 138
Dirk Vollmar Avatar answered Oct 15 '22 10:10

Dirk Vollmar