Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weirdness with StackTrace and WCF classes

We have a C# logging class that uses System.Diagnostics.StackTrace and StackFrame to obtain information about the filename, linenumber, class, and method on which logger.writeLine() was called, which are then inserted into the log message.

We've used this in console apps, in windows services, in .aspx web applications, and in .asmx web services, without problems.

I'm now working on an IIS-hosted WCF service, and I'm seeing something odd.

If I put a logger.writeLine() in the constructor of a ServiceBehavior class, and it gets to this code:

System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(true);
System.Diagnostics.StackFrame sf = st.GetFrame(2);

The first line seems to return null. Or, at least, the second throws a NullReferenceException.

Now here's the weirdness. This only happens when I'm hosting the webservice in IIS. When I'm running in Visual Studio's dev server, I have no problems.

And even in IIS, I have problems only in the constructor. Calls to logger.writeLine() work just fine, in the OperatioonContract methods and in methods called from them. It's only in the constructor, and only when hosted by IIS, that there's a problem.

If I wrap a try/catch around this, in logger.writeLine(), so that if the exception happens, we simply don't include the line information in the log file, everything works fine. Or I could just not use logging in the constructor - the only thing I was doing in the constructor was logging that the constructor had been called. So I don't actually have a problem.

But I'm wondering what is going on, and what odd corner of .NET I've stumbled into. When I run across oddities like this, and find work-arounds that seem to handle them, half the time there's some other problem I just haven't noticed yet.

So, does anyone have any explanations on why this might be happening?

like image 982
Jeff Dege Avatar asked May 11 '26 12:05

Jeff Dege


1 Answers

When running under IIS you don't have the privileges to examine code outside (above in the stack) your own assemblies.

Anyway, you can easily make your code conditional by looking at st.FrameCount.

like image 133
Henk Holterman Avatar answered May 13 '26 01:05

Henk Holterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!