asp.net-mvc - 我应该如何实现 Nlog 记录器以减少复制/粘贴的单调乏味?

标签 asp.net-mvc asp.net-web-api .net-4.5 nlog

我正在开发一个 .NET 解决方案,它将包括 MVCWeb API Controller 。在承认我应该得到比自己开发的日志记录解决方案更好的解决方案并且可以从日志记录框架中的一些功能中受益后,我选择了 NLog

我一直在四处寻找有关如何最好地将 NLog 添加到此解决方案的建议。对于初学者,让我们面对现实吧,在每个类中放置 static Logger logger = LogManager.GetCurrentClassLogger(); 有点重复。

到目前为止,我找到了两个解决方案:我的 Controller 继承自包含上述一行代码的基类,或者实现一个空接口(interface)并使用提到的扩展方法 here .

我怎样才能使记录器对所有 Controller (MVCWeb API)可用,以及当前的架构实践告诉我应该做什么?

最佳答案

看起来像那样MS suggests exactly what you're trying to avoid :

public static class ApplicationLogging
{
    public static ILoggerFactory LoggerFactory {get;} = new LoggerFactory();
    public static ILogger CreateLogger<T>() => LoggerFactory.CreateLogger<T>();
}

public class Controller
{
    ILogger Logger { get; } = ApplicationLogging.CreateLogger<Controller>();
}

The result, therefore, is an ILogger property on each class for which you wish to support logging

您可以通过某种基于约定的开发技术添加此类属性,例如,创建一个 PostSharp aspect for a whole assembly ,它将在其中找到所有需要的类并为其分配一个记录器。您甚至可以使用 Reflection.Emit.PropertyBuilder 即时创建该属性

关于asp.net-mvc - 我应该如何实现 Nlog 记录器以减少复制/粘贴的单调乏味?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42423220/

相关文章:

c# - 为什么我的 WebAPI RESTful 路由会抛出 404 错误?

.net - WPF GridSplitter 使用 MinWidth 调整大小

c# - 重定向网址不正确

c# - 防伪 token Web Api 2

asp.net - 在 asp.net mvc 中使用来电显示作为 twilio 号码

asp.net - 从跨平台移动应用程序使用 REST 和 ASP.NET Web Api 进行身份验证和授权

vb.net - 如何在我的应用程序中安装 SQL Server LocalDB?

memory-leaks - 为什么 Automapper 使用这么多内存?

c# - MySQL 连接器转换问题

c# - 发送时发生意外错误。传输流中的 EOF 或 0 字节