asp.net核心 – 在ASP.NET核心应用程序中使用NLog

前端之家收集整理的这篇文章主要介绍了asp.net核心 – 在ASP.NET核心应用程序中使用NLog前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我发现一个 CodeProject的例子,如何让这个工作,但它不工作。主要的问题似乎是Nuget中似乎不存在“Microsoft.Framework.Logging.NLog”:“1.0.0- *”包。我看过 this StackOverflow question,看了它引用的GitHub示例,但它似乎包含相同的问题。

我试图让我自己工作,我想出来的最好的是:

public class NLogLogger : ILogger
{
    public NLogLogger()
    {
        new WebLoggerConfigurer().ConfigureDefault();
    }

    public void Log(LogLevel logLevel,int eventId,object state,Exception exception,Func<object,Exception,string> formatter)
    {
        // currently need the global:: for LogLevels because our namespace contains NLog in it. Is there a better naming convention we could use instead?
        var ll = logLevel == LogLevel.Debug ? global::NLog.LogLevel.Debug
                : logLevel == LogLevel.Verbose ? global::NLog.LogLevel.Trace
                : logLevel == LogLevel.Critical ? global::NLog.LogLevel.Fatal
                : logLevel == LogLevel.Error ? global::NLog.LogLevel.Error
                : logLevel == LogLevel.Information ? global::NLog.LogLevel.Info
                : logLevel == LogLevel.Warning ? global::NLog.LogLevel.Warn
                : global::NLog.LogLevel.Off;

        LogManager.GetCurrentClassLogger().Log(ll,formatter(state,exception));
    }

    public bool IsEnabled(LogLevel logLevel)
    {
        return true;
    }

    public IDisposable BeginScopeImpl(object state)
    {
        return new Disposable(() => { });
    }
}

public class NLogLoggerProvider : ILoggerProvider
{
    public void Dispose()
    {
    }

    public ILogger CreateLogger(string categoryName)
    {
        return new NLogLogger();
    }
}

public void Configure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerFactory)
{
    loggerFactory.AddProvider(new NLogLoggerProvider());
    ..
}

BeginScopeImpl的实现似乎是一个黑客,但我不确定如何最好地实现它。

>这看起来像一个有效的实现选项吗?
>有没有更好的方法来实现BeginScopeImpl?
>还有另一种让NLog与ASP.NET 5一起工作的方法

解决方法

Microsoft.Framework.Logging.NLog已被替换为 NLog.Extensions.Logging on NuGet,由NLog团队维护。

对于ASP.NET Core,您需要NLog.Web.AspNetCore(依赖于
NLog.Extensions.Logging)

如何使用:

public void Configure(IApplicationBuilder app,ILoggerFactory loggerFactory)
{
    //add NLog to .NET Core
    loggerFactory.AddNLog();

    //Enable ASP.NET Core features (NLog.web) - only needed for ASP.NET Core users
    app.AddNLogWeb();

    //needed for non-NETSTANDARD platforms: configure nlog.config in your project root. NB: you need NLog.Web.AspNetCore package for this. 
    env.ConfigureNLog("nlog.config");
    ...
    //you could use LogManager.Configuration from here


public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    // e.g. services.AddMvc();

    //needed for NLog.Web
    services.AddSingleton<IHttpContextAccessor,HttpContextAccessor>();
}

示例如何配置,日志和过滤器,另请参见README.md in GitHub

public class HomeController : Controller
{
    protected ILogger Logger { get; }

    public HomeController(ILoggerFactory loggerFactory,IServiceProvider serviceProvider)
    {
        Logger = loggerFactory.CreateLogger(GetType().Namespace);
        Logger.LogInformation("created homeController");
    }

配置:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Warn"
      internalLogFile="c:\temp\internal.txt">


  <extensions>
    <!--enable NLog.Web for ASP.NET Core-->
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- define varIoUs log targets -->
  <targets>
    <!-- write logs to file -->
    <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
                 layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <target xsi:type="File" name="ownFile" fileName="c:\temp\nlog-own-${shortdate}.log"
              layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <target xsi:type="Null" name="blackhole" />
  </targets>

  <rules>
    <!--All logs,including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--Skip Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <logger name="*" minlevel="Trace" writeTo="ownFile" />
  </rules>
</nlog>

“nlog-own-2016-02-14.log”包含:

2016-02-14 16:27:04.0547|aspnet5application.Controllers|INFO|created homeController

2016-02-14 16:27:04.0547|aspnet5application.Controllers|INFO|created homeController

干杯,

朱利安(NLog)

编辑:更新为NLog.Web.AspNetCore 4.3

原文链接:https://www.f2er.com/aspnet/252134.html

猜你在找的asp.Net相关文章