You can create an extension method or a wrapper class, but it is not easy to get a satisfactory syntax because you need to specify some parameters ( itemIDin your example) and some only if necessary. But you cannot pass an anonymous function like object. Instead, I would use another solution that does not require extension methods or wrappers. Create the class as follows:
public sealed class Delayed {
private readonly Lazy<object> _lazy;
public Delayed(Func<object> func) {
_lazy = new Lazy<object>(func, false);
}
public override string ToString() {
var result = _lazy.Value;
return result != null ? result.ToString() : "";
}
}
This takes a function that returns an object in the constructor and will not call this function until a call is called ToString(), which, as you know, is called by log4net only if necessary (if such a debugging level is enabled). Then use like this:
logger.DebugFormat("Item {0} not found in {1}",
itemID,
new Delayed(() => string.Join(",", items.Select(i => <you get the idea>)))
);
source
share