Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging done right

Tags:

So my problem is about logging, and how to handle the log statements which can have influence on your code and your runtime behavior.

Log files... every program should write those for propper problem solving but how to do it right?

The most log-statements are verry expensive to get because they should provide usefull information and they are always built even the logging is disabled totaly.

The logging can be configured by xmls, inCode or in some settings etc. but this doesn't solve the string building problem.

For example the following code is always loading a huge lazy loaded tree which would never be loaded totaly during normal execution.

The whole tree is only created for this logging statement to be displayed in the log file

(Ok, I know..., but this is just a replacement for all the complex logging methods that exists in the most programs which should never be executed during normal release execution)

public void SomeMethod(){
    logger.Debug(someObject.GetHeavyDescriptionFromLazyTree());
}

The Method someObject.GetHeavyDescriptionFromLazyTree() is always invoked even if logging is turned off, so there are some common solutions for this problem like:

public void SomeMethod(){
#if DEBUG
    logger.Debug(someObject.GetHeavyDescriptionFromLazyTree());
#endif       
}

public void SomeMethod(){
    if(logger.DoLogDebug())
        logger.Debug(someObject.GetHeavyDescriptionFromLazyTree());
}

I think it's clear that the #if DEBUG compiler flag is no solution for productive code. If I use the logger.DoLogDebug() there would be excessive code for checking if the logging is enabled... so this can't be the solution either.

I thought the ConditionalAttribute could help but it's also bound to the compiler flags and it doesn't deactivate the call to GetHeavyDescriptionFromLazyTree

[Conditional("DEBUG")]  
public void Debug(string debugMessage) 
{ 
    Console.WriteLine(debugMessage); 
} 

So I'm looking for a logging solution which

  • is not excessive currupting my source code with debug statements
  • where the logging level is decided during runtime not at compiletime
  • where the statements are only resolved if neccessary (logLevel > definedLogLevel)

Extra loglines for the best answer ;-)

Edited: I'm looking for a solution in .NET 2.0