Last active
January 4, 2016 03:39
-
-
Save MrAntix/8563358 to your computer and use it in GitHub Desktop.
Abstract away your logger behind this Log.Delegate, only has two levels to show passing an exception, more levels easy enough. Easier than mocking ILogger in unit tests, no tie in to logging library
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 Log | |
{ | |
public const string MessageFormat = "{0:mm:ss:ffff} [{1}]: {2}"; | |
public static readonly Delegate ToConsole | |
= l => (ex, f, a) => | |
{ | |
var m = string.Format(f, a); | |
Console.WriteLine( | |
MessageFormat, DateTime.UtcNow, l, m); | |
if (ex != null) | |
{ | |
Console.WriteLine(ex); | |
} | |
}; | |
public static void Info( | |
this Delegate log, Action<Message> getMessage) | |
{ | |
if (log == null) return; | |
getMessage((f, a) => log(Level.Info)(null, f, a)); | |
} | |
public static void Error( | |
this Delegate log, Action<MessageException> getMessage) | |
{ | |
if (log == null) return; | |
getMessage(log(Level.Error)); | |
} | |
public delegate void Message(string format, params object[] args); | |
public delegate void MessageException(Exception ex, string format, params object[] args); | |
public delegate MessageException Delegate(Level level); | |
public enum Level | |
{ | |
Info, | |
Error | |
} | |
} |
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
internal static class Program | |
{ | |
static void Main() | |
{ | |
var service = new Service(Log.ToConsole) | |
service.Execute() | |
} | |
} |
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 class Service{ | |
readonly Log.Delegate _log; | |
public SomeService(Log.Delegate log){ | |
_log = log | |
} | |
public void Execute(){ | |
try | |
{ | |
var count = // do something | |
_log.Info(m => m("Done {0}", count)); | |
} | |
catch (Exception ex) | |
{ | |
_log.Fatal(m => m(ex, "Owch!")); | |
throw; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hooking up to log4net in the DI container (Windsor)