Skip to content

Instantly share code, notes, and snippets.

@DTTerastar
Last active December 31, 2015 01:49
Show Gist options
  • Save DTTerastar/7917094 to your computer and use it in GitHub Desktop.
Save DTTerastar/7917094 to your computer and use it in GitHub Desktop.
Log a function call easily w/ log4net. Shouldn't have performance impact if not set to log. Uses [CallerMemberName] so you don't have to supply it. Usage: logger.InfoCall(()=>new { param1, param2, param3})
public static class LogExtensions
{
public static void InfoCall(this ILog log, Func<object> args = null, [CallerMemberName] string name = "")
{
if (log.IsInfoEnabled)
log.Info(new Message(name, (args != null) ? args() : null));
}
public static void DebugCall(this ILog log, Func<object> args = null, [CallerMemberName] string name = "")
{
if (log.IsDebugEnabled)
log.Debug(new Message(name, (args != null) ? args() : null));
}
private class Message
{
private readonly object _args;
private readonly string _name;
public Message(string name, object args)
{
_name = name;
_args = args;
}
public override string ToString()
{
var sb = new StringBuilder("Call");
sb.AppendFormat(" {0}(", _name);
if (_args != null)
{
bool addComma = false;
foreach (PropertyDescriptor a in TypeDescriptor.GetProperties(_args))
{
sb.AppendFormat(addComma ? ", {0}: '{1}'" : "{0}: '{1}'", a.Name, a.GetValue(_args));
addComma = true;
}
}
sb.Append(")");
return sb.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment