Last active
December 31, 2015 01:49
-
-
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})
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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