I have a method in ASP.NET application that works good but sometimes it fails. I need some kind of error logging or tracing. If you don’t want to write stupid messages everywhere in your code, you have some possibilities.
In debug mode:
1. Embrace your code in try-catch block. Compile the application in debug mode and place .pdb file along with .exe file. When the error is occurred, exception will show the line number.
2. You can write trace info manually as described by Scott Hanselman inĀ Getting the Line Number and File Name from C#.
1 2 3 4 5 6 7 8 9 |
using System.Diagnostics; static void WriteMessage(string message) { StackFrame callStack = new StackFrame(1, true); Console.WriteLine(message + " at line " + callStack.GetFileLineNumber() + " (" + callStack.GetMethod().Name + ")"); } |
.pdb file is necessary here, or you’ll see 0 instead of a line number.
In release mode:
Thanks to Marc Gravell https://stackoverflow.com/a/14122771, but you need .NET Framework 4.5 or higher here.
1 2 3 4 5 6 7 8 9 |
using System.Runtime.CompilerServices; static void WriteMessage(string message, [CallerLineNumber] int lineNumber = 0, [CallerMemberName] string caller = null) { Console.WriteLine(message + " at line " + lineNumber + " (" + caller + ")"); } |