#CallerFilePath
Explore tagged Tumblr posts
multidimensionalsock · 3 months ago
Text
Tracking who called your function in C#
I was making a logging class yesterday and wanted a way to keep track of where the function was being called from so I could trace errors to their source easily. Having to write in the class/function each time Log() is called is tedious for the user, so instead I used attributes
The Log function is defined as:
public static void Log(LogType logType, string logDescription, [CallerFilePath] string callerFilePath = "", [CallerMemberName] string source = "")
Because a default value has been set for callerFilePath and source, when the user calls the function they only need to set logType and logDescription. If a value isn't set by the user, then because of the attributes, C# is able to track where the function was called from.
[CallerFilePath] - is used to get the directory of the file the function was called from, this is relative to the position on your local device, not relative to the project. If you split all your classes into different files, this can be used to get the class name.
[CallerMemberName] - can directly get the function name for the function which called Log. This will be passed as a string, so it multiple classes share the same function names, it can be hard to trace which called the function.
[CallerFilePath] gives the entire directory of the file, in order to extract just the class name, I used the following:
int index = callerFilePath.LastIndexOf("\\") + 1;
callerFilePath = callerFilePath.Substring(index, callerFilePath.LastIndexOf(".") - index);
This gets the index of the last time \\ is used in the directory path string, and then it gets the last index of where . Was used (for the file name e.g. Logger.cs), and subtracts the index of the first letter we want of our substring to get the total string length we want.
When I add the string to the database using $"{callerFilePath}.{source}", it will populate the database like this:
Tumblr media
4 notes · View notes
ryadel · 3 years ago
Link
0 notes