Couldn’t remember better title, feel free to change it to something better 🙂
My application contains a lot of logging statements, something like this:
var logger = new Logger(/*..get flag from settings if the logger should be active..*/);
// ....
logger.LogActivity(..serialize an object..);
//...
logger.LogActivity(..get another object's expensive overriden ToString method..);
//...
logger.LogActivity(..log something new..);
Logger class:
public class Logger
{
private readonly bool _isActive;
public Logger(bool isActive)
{
_isActive = isActive;
}
public void LogActivity(string activity)
{
if (_isActive)
{
// Save activity to Database.
}
}
}
When I disable logger in settings (so the _isActive field in Logger class is false), then nothing is saved to database. But all the expressions in the Logger.LogActivity methods are still evaluated (for instance ..serialize object.. in previous example) and this slows down my application.
I could use log statements like this:
var logger = new Logger(/*..get flag from settings if the logger should be active..*/);
// ....
if (loggerIsActive) logger.LogActivity(..serialize an object..);
//...
if (loggerIsActive) logger.LogActivity(..get another object's expensive overriden ToString method..);
//...
if (loggerIsActive) logger.LogActivity(..log something new..);
But it would be much better to change only LogActivity method… Is it possible to somehow change only LogActivity method so that in case, when the logger is disabled, the expressions in LogActivity call aren’t evaluated? Well – I would be surprised if this is possible in C#, but is there any other way/pattern to do this?
You could add an overload that takes a
Func<string>that would generate the string to be logged.Then use it like this: