当前位置:  开发笔记 > 编程语言 > 正文

在ASP.NET Core应用程序中使用NLog

如何解决《在ASP.NETCore应用程序中使用NLog》经验,为你挑选了2个好方法。

我找到了一个CodeProject,其中有一个如何使其工作的示例,但它不起作用.主要问题似乎是"Microsoft.Framework.Logging.NLog": "1.0.0-*"Nuget中似乎不存在包.我查看了这个StackOverflow问题并查看了它引用的GitHub示例,但它似乎包含相同的问题.

我试图让它自己工作,我提出的最好的是以下内容:

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

    public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func 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一起使用?

Julian.. 46

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

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

如何使用:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 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();

    //configure nlog.config in your project root. 
    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();
}

示例如何配置,记录和过滤,另请参阅GitHub中的README.md.

using NLog.Web;
using Microsoft.Extensions.Logging;

public static void Main(string[] args)
{
    // NLog: setup the logger first to catch all errors
    var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    try
    {
        logger.Debug("init main");
        CreateWebHostBuilder(args).Build().Run(); 
    }
    catch (Exception ex)
    {
        //NLog: catch setup errors
        logger.Error(ex, "Stopped program because of exception");
        throw;
    }
    finally
    {
        // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
        NLog.LogManager.Shutdown();
    }
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup()
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
        })
        .UseNLog();  // NLog: setup NLog for Dependency injection

配置:

public class HomeController : Controller
{
    public HomeController(ILogger logger)
    {
        logger.LogInformation("created homeController");
    }

"nlog-own-2016-02-14.log"包含:

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

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

干杯,

朱利安(NLog)

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



1> Julian..:

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

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

如何使用:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 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();

    //configure nlog.config in your project root. 
    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();
}

示例如何配置,记录和过滤,另请参阅GitHub中的README.md.

using NLog.Web;
using Microsoft.Extensions.Logging;

public static void Main(string[] args)
{
    // NLog: setup the logger first to catch all errors
    var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    try
    {
        logger.Debug("init main");
        CreateWebHostBuilder(args).Build().Run(); 
    }
    catch (Exception ex)
    {
        //NLog: catch setup errors
        logger.Error(ex, "Stopped program because of exception");
        throw;
    }
    finally
    {
        // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
        NLog.LogManager.Shutdown();
    }
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup()
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
        })
        .UseNLog();  // NLog: setup NLog for Dependency injection

配置:

public class HomeController : Controller
{
    public HomeController(ILogger logger)
    {
        logger.LogInformation("created homeController");
    }

"nlog-own-2016-02-14.log"包含:

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

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

干杯,

朱利安(NLog)

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



2> 小智..:

更新到Julian的答案:NLog.Framework.Logging标记为过时,改为使用NLog.Extensions.Logging(只是包重命名).此外,env.ConfigureNLog("nlog.config");仅适用于Visual Studio(IIS Express)中的调试.在测试环境中向常规IIS发布服务后,它无法启动500 internal server error.花了很长时间才弄清楚服务nlog.config在启动时找不到了.终于找到了NLog问题的解决方案:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationEnvironment appEnv)
{
    ...
    env.ConfigureNLog(Path.Combine(appEnv.ApplicationBasePath, "nlog.config"));
    ...
}

问题是当调试本地工作目录是你的项目目录nlog.config内部,但在发布到IIS后,所有源文件都在%PATH_TO_PUBLISHED_SERVICE%\approot\src\%PROJECT_NAME%\工作目录中%PATH_TO_PUBLISHED_SERVICE%\.


更新:此问题已修复
推荐阅读
和谐啄木鸟
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有