Logger wrapper best practice

泪湿孤枕 提交于 2019-11-26 01:37:04

问题


I want to use a nlogger in my application, maybe in the future I will need to change the logging system. So I want to use a logging facade.

Do you know any recommendations for existing examples how to write those ones ? Or just give me link to some best practice in this area.


回答1:


I used to use logging facades such as Common.Logging (even to hide my own CuttingEdge.Logging library), but nowadays I use the Dependency Injection pattern and this allows me to hide loggers behind my own (simple) abstraction that adheres to both Dependency Inversion Principle and the Interface Segregation Principle (ISP) because it has one member and because the interface is defined by my application; not an external library. Minimizing the knowledge that the core parts of your application have about the existence of external libraries, the better; even if you have no intention to ever replace your logging library. The hard dependency on the external library makes it harder to test your code, and complicates your application with an API that was never designed specifically for your application.

This is what the abstraction often looks like in my applications:

public interface ILogger
{
    void Log(LogEntry entry);
}

public enum LoggingEventType { Debug, Information, Warning, Error, Fatal };

// Immutable DTO that contains the log information.
public class LogEntry 
{
    public readonly LoggingEventType Severity;
    public readonly string Message;
    public readonly Exception Exception;

    public LogEntry(LoggingEventType severity, string message, Exception exception = null)
    {
        if (message == null) throw new ArgumentNullException("message");
        if (message == string.Empty) throw new ArgumentException("empty", "message");

        this.Severity = severity;
        this.Message = message;
        this.Exception = exception;
    }
}

Optionally, this abstraction can be extended with some simple extension methods (allowing the interface to stay narrow and keep adhering to the ISP). This makes the code for the consumers of this interface much simpler:

public static class LoggerExtensions
{
    public static void Log(this ILogger logger, string message) {
        logger.Log(new LogEntry(LoggingEventType.Information, message));
    }

    public static void Log(this ILogger logger, Exception exception) {
        logger.Log(new LogEntry(LoggingEventType.Error, exception.Message, exception));
    }

    // More methods here.
}

Since the interface contains just a single method, you can easily create an ILogger implementation that proxies to log4net, to Serilog, Microsoft.Extensions.Logging, NLog or any other logging library and configure your DI container to inject it in classes that have a ILogger in their constructor.

Do note that having static extension methods on top of an interface with a single method is quite different from having an interface with many members. The extension methods are just helper methods that create a LogEntry message and pass it through the only method on the ILogger interface. The extension methods become part of the consumer's code; not part of the abstraction. Not only does this allow the extension methods to evolve without the need to change the abstraction, the extension methods and the LogEntry constructor are always executed when the logger abstraction is used, even when that logger is stubbed/mocked. This gives more certainty about the correctness of calls to the logger when running in a test suite. The one-membered interface makes testing much easier as well; Having an abstraction with many members makes it hard to create implementations (such as mocks, adapters and decorators).

When you do this, there is hardly ever any need for some static abstraction that logging facades (or any other library) might offer.




回答2:


I used the small interface wrapper + adapter from https://github.com/uhaciogullari/NLog.Interface that is also available via NuGet:

PM> Install-Package NLog.Interface 



回答3:


Generally I prefer to create an interface like

public interface ILogger
{
 void LogInformation(string msg);
 void LogError(string error);
}

and in the runtime i inject a concrete class that is implemented from this interface.




回答4:


A great solution to this problem has emerged in the form of the LibLog project.

LibLog is a logging abstraction with built-in support for major loggers including Serilog, NLog, Log4net and Enterprise logger. It is installed via the NuGet package manager into a target library as a source (.cs) file instead of a .dll reference. That approach allows the logging abstraction to be included without forcing the library to take on an external dependency. It also allows a library author to include logging without forcing the consuming application to explicitly provide a logger to the library. LibLog uses reflection to figure out what concrete logger is in use and hook up to it up without any explicit wiring code in the library project(s).

So, LibLog is a great solution for logging within library projects. Just reference and configure a concrete logger (Serilog for the win) in your main application or service and add LibLog to your libraries!




回答5:


As of now, the best bet is to use the Microsoft.Extensions.Logging package (as pointed out by Julian). Most logging framework can be used with this.

Defining your own interface, as explained in Steven's answer is OK for simple cases, but it misses a few things that I consider important:

  • Structured logging and de-structuring objects (the @ notation in Serilog and NLog)
  • Delayed string construction/formatting: as it takes a string, it has to evaluate/format everything when called, even if in the end the event will not be logged because it's below the threshold (performance cost, see previous point)
  • Conditional checks like IsEnabled(LogLevel) which you might want, for performances reasons once again

You can probably implement all this in your own abstraction, but at that point you'll be reinventing the wheel.




回答6:


Instead of writing your own facade, you could either use Castle Logging Services or Simple Logging Façade.

Both include adapters for NLog and Log4net.




回答7:


Since 2015 you could also use .NET Core Logging if you're building .NET core applications.

The package for NLog to hook into is:

  • NLog.Web.AspNetCore for ASP.NET Core users
  • NLog.Extensions.Logging for .NET Core users, e.g. console projects


来源:https://stackoverflow.com/questions/5646820/logger-wrapper-best-practice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!