Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do __LINE__ __FILE__ equivalents exist in C#?

Tags:

c#

logging

For logging purposes

__LINE__  __FILE__  

were my friends in C/C++. In Java to get that information I had to throw an exception and catch it. Why are these old standbys so neglected in the modern programming languages? There is something magical about their simplicity.

like image 905
ojblass Avatar asked Mar 30 '09 06:03

ojblass


People also ask

What is __ LINE __ in C?

__LINE__ is a preprocessor macro that expands to current line number in the source file, as an integer. __LINE__ is useful when generating log statements, error messages intended for programmers, when throwing exceptions, or when writing debugging code.

What is __ file __ in C?

__FILE__ This macro expands to the name of the current input file, in the form of a C string constant. This is the path by which the preprocessor opened the file, not the short name specified in ' #include ' or as the input file name argument. For example, "/usr/local/include/myheader.

What is a macro in C++?

Identifiers that represent statements or expressions are called macros. In this preprocessor documentation, only the term "macro" is used. When the name of a macro is recognized in the program source text, or in the arguments of certain other preprocessor commands, it's treated as a call to that macro.


2 Answers

Caller Information has been added to .NET 4.5. This will be compiled, a big improvement over having to examine the stack trace manually.

public void Log(string message,         [CallerFilePath] string filePath = "",         [CallerLineNumber] int lineNumber = 0) {     // Do logging } 

Simply call it in this manner. The compiler will fill in the file name and line number for you:

logger.Log("Hello!"); 
like image 65
roken Avatar answered Sep 21 '22 03:09

roken


It is uglier, but you can do something like this in C# using the StackTrace and StackFrame classes:

StackTrace st = new StackTrace(new StackFrame(true)); Console.WriteLine(" Stack trace for current level: {0}", st.ToString()); StackFrame sf = st.GetFrame(0); Console.WriteLine(" File: {0}", sf.GetFileName()); Console.WriteLine(" Method: {0}", sf.GetMethod().Name); Console.WriteLine(" Line Number: {0}", sf.GetFileLineNumber()); Console.WriteLine(" Column Number: {0}", sf.GetFileColumnNumber()); 

Of course, this comes with some overhead.

like image 25
Ed S. Avatar answered Sep 22 '22 03:09

Ed S.