Microsoft.Extensions.Logging与日志 [英] Microsoft.Extensions.Logging Vs. NLog

查看:3178
本文介绍了Microsoft.Extensions.Logging与日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多帖子都提到了Microsoft.Extensions.Logging和NLog的用法.

I see a lot of posts mentioning usage of Microsoft.Extensions.Logging together with NLog.

我想更好地了解Microsoft.Extensions.Logging的用途是什么?

I'd like to better understand what Microsoft.Extensions.Logging is used for?

特别是为什么需要它,或者与NLog一起使用它有什么好处?

And specifically why is it needed or what's the benefit of using it together with NLog?

推荐答案

使用NLog,您可以执行以下操作:

With NLog you could do:

var logger = NLog.LogManager.GetCurrentClassLogger();
logger.Info("Hello {Name}", "Earth");

这适用于所有平台和所有框架.

That works for all platforms and all frameworks.

随着.NET Core的引入,Microsoft引入了日志记录抽象-Microsoft.Extensions.Logging.您可以在项目中使用该日志记录抽象,并将其与NLog集成.

With the introduction of .NET Core, a logging abstraction is introduced by Microsoft - Microsoft.Extensions.Logging. You could use that logging abstraction in your project and integrate it with NLog.

例如,在ASP.NET Core中,您可以注入Microsoft.Extensions.Logging.ILogger<HomeController>,然后可以将日志发送到NLog. (请参阅 ASP.NET Core 2入门· NLog/NLog Wiki )

For example in ASP.NET Core you could inject Microsoft.Extensions.Logging.ILogger<HomeController> and that could send the logs to NLog. (see Getting started with ASP.NET Core 2 · NLog/NLog Wiki)

using Microsoft.Extensions.Logging;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        _logger.LogInformation("Index page says hello {Name}", "Universe");
        return View();
    }

包裹

对于NLog和Microsoft.Extensions.Logging,有以下软件包:

Packages

For NLog and Microsoft.Extensions.Logging there are the following packages:

  • The .NET core logging abstractions are in the package Microsoft.Extensions.Logging.Abstractions
  • The NLog integration for those abstractions is in package NLog.Extensions.Logging. You could use this package for .NET Core console applications.
  • For ASP.NET Core, there is an optimized package NLog.Web.AspNetCore which uses NLog.Extensions.Logging

直接使用NLog的优点

Pros of using NLog directly

  • 最佳表现
  • 记录器API的更多选项,例如Logger.WithProperty(..)
  • 适用于所有平台
  • 不需要依赖注入,可以节省复杂性.
  • Best performance
  • More options with the logger API, e.g. Logger.WithProperty(..)
  • Works in all platforms
  • No Dependency Injection needed which saves complexity.

通过Microsoft.Extensions.Logging使用NLog的优点:

Pros of using NLog via Microsoft.Extensions.Logging:

  • 与ASP.NET Core完全集成,例如微软还向记录器API写入内容,并且也会被NLog捕获(并可能进行过滤)
  • 写入日志抽象将使您的代码与日志库无关.
  • 与.NET Core依赖项注入配合得很好

这篇关于Microsoft.Extensions.Logging与日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆