Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to have entity framework logging set to debug window in production source code?

Is it ok to have this line in production source code? What kind of performance penalties it produces? I know that Debug.WriteLine is not emitted to assembly built with release configuration.

ddiCatalogEntities.Database.Log = msg => Debug.WriteLine(msg);

This line should log Entity framework log output to Visual Studio Debug Console while running in Debug mode.

#if DEBUG 
ddiCatalogEntities.Database.Log = msg => Debug.WriteLine(msg);
#endif

Would you prefer solution above?

like image 434
Fosna Avatar asked Aug 20 '14 08:08

Fosna


1 Answers

Firstly, note that you cannot point a normal delegate at a method with ConditionalAttribute.

However, you are using a lambda, so that compiles OK. But what does it actually compile to?

Consider this code:

Action<string> print = message => Debug.WriteLine(message);
print("TEST");

For a debug build this compiles to:

Action<string> print = delegate (string message) {
    Debug.WriteLine(message);
};
print("TEST");

For a release build, it compiles to:

Action<string> print = delegate (string message) {
};
print("TEST");

In both cases, a delegate is created and called - so in both cases you will have the overhead of delegate creation and calling (the parameter is pushed on the stack), even though the release version doesn't actually do anything.

So for your case the difference between using #if DEBUG or not is as follows:

  • If you use #if DEBUG then there is no overhead at all, and the Log property will not be set.
  • Otherwise, you have the overhead of setting the Log property and then it doing nothing when it is called.

In many cases the overhead is so small that you don't mind - and also it's quite nice to ensure that the Log property is always set to something (defaulting to a "do nothing" delegate) so you don't need to check it against null before referencing it each time.

On the other hand, the use of #if DEBUG makes it much clearer what is going on. The way that a lambda and a method defined with ConditionalAttribute interacts is not totally obvious!

All of which is a roundabout way of saying: Weigh up the pros and cons and make your own choice. ;)

like image 137
Matthew Watson Avatar answered Sep 28 '22 18:09

Matthew Watson