Reputation: 40018
Hi I want to implement the Logger class so that I can log messages in the log file(a text file).
I'm able to log these messages to a file but I need some more description like which method has called this Log
method.
E.g.
class MyClass
{
void DoSomething()
{
Logger.Log("Doing my job");
}
}
Then the Log.txt file should contain message like this
Date&time:Line No. 5:MyClass:DoSomething:Doing my job
It's easy to get the date&time and the Message, but I'm not getting a way to get the method name/class name/line number.
I tried to overloading Log
method as
Logger.Log(this,"your Message");
In this I can get the class name but not method name/line number (method name is important than line number I can remove line number)
Upvotes: 1
Views: 243
Reputation: 17865
What you're looking for are the caller information attributes that have become available with .NET Framework 4.5:
void Log(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
// output the info to file
}
You can still call the Log
method just like you do now, the compiler will fill in the values for the optional parameters.
You can't get the class name this way, but if the combination of method name and file name is not enough for you, you can still get the class name as you have already suggested yourself.
Upvotes: 4