Skip to content

Instantly share code, notes, and snippets.

@Philo
Last active August 29, 2015 14:22
Show Gist options
  • Save Philo/b43a23ae6f0716f73632 to your computer and use it in GitHub Desktop.
Save Philo/b43a23ae6f0716f73632 to your computer and use it in GitHub Desktop.
Func's for Logging
public class MyObject {
public string Message {get;set; }
}
public class Program {
public static void Main() {
MyObject myObj = null;
Log(myObj.Message); // this will explode in your face with an exception
Log(() => return myObj.Message); // this will actually log another message because we caught the exception when the func was invoked
Log(() => GetLogMessage(myObj));
}
private string GetLogMessage(MyObject obj) {
return obj.Message;
}
public void Log(string logMessage, Exception exception) {
}
public void Log(string logMessage) {
}
public void Log(Func<string> logMessage) {
try {
var resultOfExecutingFunc = logMessage(); // invoke now so I can catch the exception and stop my app breaking
Log(resultOfExecutingFunc);
} catch(Exception ex) {
Log("unable to log message due to exception", ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment