.Net has very useful Caller member attributes that you can use for such things. Put them on a method and the compiler will set the values ββto the member name, line number or path to the file where the method was called.
public void Log(Exception ex, [CallerFilePath]string callerFilePath = null, [CallerMemberName]string callerMemberName = null, [CallerLineNumber]int callerLineNumber = 0) { Console.WriteLine($"Message: {ex.Message} # File: {callerFilePath} # Line: {callerLineNumber} # Member: {callerMemberName}" ); }
So, every time you call the Log method, you get the line number and the path to the file where the method was called. This is also very cheap, because the compiler inserts them as constants, instead of pulling them with reflection.
Please note that this log indicates the place where you called the log method, not the original location where the exception was sent, but depending on your needs. That might be enough.
source share