One of the new features of Visual Studio 11 and the .NET Framework 4.5 are the Caller attributes:
- CallerMemberName: allows you to obtain the method or property name of the caller to the method.
- CallerFilePath: allows you to obtain the full path of the source file that contains the caller. This is the file path at compile time.
- CallerLineNumber: allows you to obtain the line number in the source file at which the method is called.
These attributes help to simplify the code in certain scenarios, such as logging or when using the INotifyPropertyChanged interface (as in MVVM) and you need to pass the name of the calling property.
Here is a very simple example of their use in logging:
class Logger
{
public static void LogMessage(string msg,
[CallerMemberName] string member = "",
[CallerFilePath] string file = "",
[CallerLineNumber] int line = 0)
{
string message = String.Format("{0} : Member {1} in file {2} at line {3} = {4}",
DateTime.Now.ToString(), member, file, line, msg);
Debug.WriteLine(message);
Console.WriteLine(message);
}
}
To log an entry, you simply need to provide the desired message and the attributes will take care of the rest!
class Program
{
static void Main(string[] args)
{
Logger.LogMessage("Error!!!");
Console.ReadLine();
}
}
As simple as that!
Happy logging ;)