Reputation: 2257
static void WriteLog(String FullPath, String Log)
{
try
{
if (File.Exists(FullPath))
{
FileInfo Fi = new FileInfo(FullPath);
if (Fi.Length > MaxFileSize * 1024)
{
if (File.Exists(FullPath + ".Old"))
{
File.Delete(FullPath + ".Old");
}
File.Move(FullPath, FullPath + ".Old");
}
}
string currentFile = System.IO.Path.GetFileName(new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName());
int currentLine = new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber();
File.AppendAllText(@FullPath, "[ " + MyTime.Now.ToString("dd/MM/yy HH:mm:ss") + " ] " + currentFile + "," + currentLine + "," + Log.Replace("\r\n", "\r\n ") + "\r\n");
}
catch (Exception ex)
{
utilities.Log(ex.ToString());
}
}
Hi, I'm writing a Logging utility in my program. Part of the log, I would like to show the currentFile name and the Current Line number in the program execution using stacktrace. However, Then following line of codes would return the log utiltiy's currentfile and line.
string currentFile = System.IO.Path.GetFileName(new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName());
int currentLine = new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber();
How do I make the stacktrace return the calling function's Current File and Line number?
Upvotes: 0
Views: 1217
Reputation: 4934
By using the Caller Info attributes on your method properties, you can get the file name, member/method name, and line number.
public void TraceMessage(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0){
Trace.WriteLine("message: " + message);
Trace.WriteLine("member name: " + memberName);
Trace.WriteLine("source file path: " + sourceFilePath);
Trace.WriteLine("source line number: " + sourceLineNumber);
}
Note that this information might not be available if you do not have the debug symbols for your assembly loaded. (matching .pdb file for each of your .dll files)
Upvotes: 3
Reputation: 41393
You would need to get the frame before the current one:
var previousFrame = new System.Diagnostics.StackTrace(true).GetFrame(1);
Upvotes: 2