我看到很多帖子都提到Microsoft.Extensions.Logging与NLog一起使用。
我想更好地了解Microsoft.Extensions.Logging的用途是什么?
特别是为什么需要它,或者与NLog一起使用它有什么好处?
答案 0 :(得分:6)
使用NLog,您可以:
var logger = NLog.LogManager.GetCurrentClassLogger();
logger.Info("Hello {Name}", "Earth");
这适用于所有平台和所有框架。
随着.NET Core的引入,Microsoft引入了日志记录抽象-Microsoft.Extensions.Logging。您可以在项目中使用该日志记录抽象并将其与NLog集成。
例如,在ASP.NET Core中,您可以注入Microsoft.Extensions.Logging.ILogger<HomeController>
,然后将日志发送到NLog。 (请参阅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,有以下软件包:
直接使用NLog的优点
Logger.WithProperty(..)
通过Microsoft.Extensions.Logging使用NLog的优点:
答案 1 :(得分:0)
Microsoft.Extensions.Logging
用于依赖注入,这对于单元测试很方便:您可以实现带有 LoggedText 属性的记录器来支持 Assert.IsTrue(_logger.LoggedText.Contains("expected value"))
。以下示例说明了这样一个实现 Microsoft.Extensions.Logging.ILogger<T>
的类,并且(为了好玩)还使用了 Julian 的将消息发送到 NLog 的建议:
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyDomain.Tests
{
internal class WrappedNLogger<T> : ILogger<T>
{
private StringBuilder _sb = new StringBuilder(); //Support Assert.IsTrue(_logger.LoggedText == "expected value")
private NLog.Logger _nlog = NLog.LogManager.GetCurrentClassLogger(); //support use of NLog
public IDisposable BeginScope<TState>(TState state) => default;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
var jsonLine = JsonConvert.SerializeObject(new
{
timestamp = DateTime.Now.ToLongTimeString(),
logLevel,
eventId,
parameters = (state as IEnumerable<KeyValuePair<string, object>>)?.ToDictionary(i => i.Key, i => i.Value),
message = formatter(state, exception),
exception = exception?.GetType().Name
});
_sb.AppendLine(jsonLine);
NLog.LogLevel nloglevel = logLevel == LogLevel.Debug ? NLog.LogLevel.Debug
: logLevel == LogLevel.Information ? NLog.LogLevel.Info
: logLevel == LogLevel.Warning ? NLog.LogLevel.Warn
: logLevel == LogLevel.Error ? NLog.LogLevel.Error
: logLevel == LogLevel.Critical ? NLog.LogLevel.Fatal : NLog.LogLevel.Trace;
_nlog.Log(nloglevel, jsonLine);
}
public string LoggedText { get => _sb.ToString(); }
}
}