我想在我的应用程序中使用 nlogger,也许将来我需要更改日志记录系统。 所以我想使用日志外观。
您是否知道对现有示例如何编写这些示例的任何建议? 或者只是给我链接到这个领域的一些最佳实践。
最佳答案
我曾经使用日志外观,例如 Common.Logging (甚至隐藏我自己的 CuttingEdge.Logging 库),但现在我使用 Dependency Injection pattern .这允许我将记录器隐藏在应用程序定义的抽象背后,该抽象遵循 Dependency Inversion Principle和 Interface Segregation Principle (ISP),因为它只有一个成员,而且接口(interface)是由我的应用程序定义的;不是外部图书馆。
尽量减少应用程序核心部分对外部库存在的了解越好;即使您无意更换您的日志记录库。对外部库的硬依赖使得测试代码变得更加困难,并且使用从未专门为您的应用程序设计的 API 使您的应用程序变得复杂。
在我的应用程序中,抽象通常是这样的:
public interface ILogger
{
void Log(LogEntry entry);
}
public sealed class ConsoleLogger : ILogger
{
public void Log(LogEntry entry)
}
public enum LoggingEventType { Debug, Information, Warning, Error, Fatal };
// Immutable DTO that contains the log information.
public struct LogEntry
{
public LoggingEventType Severity { get; }
public string Message { get; }
public Exception Exception { get; }
public LogEntry(LoggingEventType severity, string msg, Exception ex = null)
{
if (msg is null) throw new ArgumentNullException("msg");
if (msg == string.Empty) throw new ArgumentException("empty", "msg");
this.Severity = severity;
this.Message = msg;
this.Exception = ex;
}
}
可选地,可以使用一些简单的扩展方法来扩展此抽象(允许接口(interface)保持窄并保持遵守 ISP)。这使得此接口(interface)的使用者的代码更加简单:
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 ex) =>
logger.Log(new LogEntry(LoggingEventType.Error, ex.Message, ex));
// More methods here.
}
因为该接口(interface)只包含一个方法,所以很容易创建一个 ILogger
实现 proxies to log4net , to Serilog , Microsoft.Extensions.Logging 、NLog 或任何其他日志记录库,并配置您的 DI 容器以将其注入(inject)在其构造函数中具有 ILogger
的类中。创建写入控制台的实现或可用于单元测试的伪实现也很容易,如下面的 list 所示:
public class ConsoleLogger : ILogger
{
public void Log(LogEntry entry) => Console.WriteLine(
$"[{entry.Severity}] {DateTime.Now} {entry.Message} {entry.Exception}");
}
public class FakeLogger : List<LogEntry>, ILogger
{
public void Log(LogEntry entry) => this.Add(entry);
}
在具有单个方法的接口(interface)之上拥有静态扩展方法与拥有具有许多成员的接口(interface)是完全不同的。扩展方法只是创建 LogEntry
消息并通过 ILogger
接口(interface)上的唯一方法传递它的辅助方法。这些扩展方法本身不包含 Volatile Behavior他们自己,因此不会妨碍可测试性。如果愿意,您可以轻松地测试它们,并且它们会成为消费者代码的一部分;不是抽象的一部分。
这不仅允许扩展方法在不需要更改抽象的情况下发展,扩展方法和 LogEntry
构造函数总是在使用记录器抽象时执行,即使该记录器是 stub / mock 。这使得在测试套件中运行时调用记录器的正确性更加确定。我曾多次搬起石头砸自己的脚,我在单元测试期间成功调用了使用过的第三方记录器抽象,但在生产中执行时仍然失败。
单成员界面也让测试变得更加容易;具有许多成员的抽象使得很难创建实现(例如模拟、适配器和装饰器)。
当您这样做时,几乎不需要日志外观(或任何其他库)可能提供的一些静态抽象。
尽管如此,即使使用这种 ILogger
设计,也更喜欢以这样的方式设计您的应用程序,即只有少数类需要依赖于您的 ILogger
抽象。 This answer更详细地讨论了这一点。
关于c# - 记录器包装器最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5646820/