Skip to content

Instantly share code, notes, and snippets.

@MrAntix
Last active January 4, 2016 03:39
Show Gist options
  • Save MrAntix/8563358 to your computer and use it in GitHub Desktop.
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
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
}
}
internal static class Program
{
static void Main()
{
var service = new Service(Log.ToConsole)
service.Execute()
}
}
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;
}
}
}
@MrAntix
Copy link
Author

MrAntix commented Jan 22, 2014

Hooking up to log4net in the DI container (Windsor)

public static class WindsorConfig
{
    public static void Register(
        IWindsorContainer container)
    {
        container.Register(
            Component.For<WindowsService>());

        RegisterLogging(container);
    }

    static void RegisterLogging(IWindsorContainer container)
    {
        XmlConfigurator.Configure();
        var log = LogManager.GetLogger(Settings.Default.LogName);

        container.Register(
            Component.For<Log.Delegate>()
                     .Instance(GetLogDelegate(log)));
    }

    static Log.Delegate GetLogDelegate(ILog log)
    {
        return
            level => (ex, format, args) =>
                {
                    var message = string.Format(format, args);
                    switch (level)
                    {
                        case Log.Level.Error:
                            log.Error(message, ex);
                            break;

                        default:
                            log.Info(message);
                            break;
                    }
                };
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment