Use NLog in ASP.NET Core application

后端 未结 4 1993
南笙
南笙 2020-12-02 15:48

I found a CodeProject with an example of how to get this to work, but it doesn\'t work. The main problem seems to be that the \"Microsoft.Framework.Logging.NLog\": \"

相关标签:
4条回答
  • 2020-12-02 16:02

    Update to Julian's answer: NLog.Framework.Logging is marked obsolete, use NLog.Extensions.Logging instead (just a package rename, though). Also,env.ConfigureNLog("nlog.config"); works fine only for debugging in Visual Studio (IIS Express). After I've published service to regular IIS on test environment, it failed to start with 500 internal server error. Spent quite a long time to figure out service couldn't find nlog.config at startup anymore. Finally found solution in NLog issues:

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

    Matter is when debugging locally working directory is your project's directory with nlog.config inside, but after publishing to IIS all source files are in %PATH_TO_PUBLISHED_SERVICE%\approot\src\%PROJECT_NAME%\ while working directory is %PATH_TO_PUBLISHED_SERVICE%\.

    0 讨论(0)
  • 2020-12-02 16:12

    Microsoft.Framework.Logging.NLog has been replaced by NLog.Extensions.Logging on NuGet, which is maintained by the NLog team.

    For ASP.NET Core, you need NLog.Web.AspNetCore (which has a dependency on NLog.Extensions.Logging).

    How to use:

    Setup

    NLog needs to be enabled so it will integrate into the DI and log API of ASP.NET Core. This will result that all logs written by externals (e.g. Microsoft) will be also sent to NLog - you could filter that out in the NLog's config (without performance impact).

    Since ASP.NET Core 2 there are new approach.

    ASP.NET Core 1

    In ASP.NET Core in Configure and optionally ConfigureServices needs to be updated.

    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<IHttpContextAccessor, HttpContextAccessor>();
    }
    

    ASP.NET Core 2

    For ASP.NET Core 2, the setup is different than in ASP.NET Core 1

    Set-up NLog in program.cs:

    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<Startup>()
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            })
            .UseNLog();  // NLog: setup NLog for Dependency injection
    

    ASP.NET Core 3

    There are some small changes compared to ASP.NET Core 2, e.g. there is an IHostBuilder instead of the IWebHostBuilder.

    Set-up NLog in program.cs:

    using System;
    using NLog.Web;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Hosting;
    
    public static void Main(string[] args)
    {
        var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        try
        {
            logger.Debug("init main");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception exception)
        {
            //NLog: catch setup errors
            logger.Error(exception, "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 IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
          .ConfigureWebHostDefaults(webBuilder =>
          {
              webBuilder.UseStartup<Startup>();
          })
          .ConfigureLogging(logging =>
          {
              logging.ClearProviders();
              logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
          })
          .UseNLog();  // NLog: Setup NLog for Dependency injection
    

    Write logs

    Inject an ILogger with the class type as generic argument.

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

    Configure NLog rules

    Example on how to configure, log and filter.

    Create an nlog.config (for more reading about nlog.config, see docs).

    This example will create 2 files, one with all the logs (including Microsoft's) and a file with only your logs.

    <?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}" />
    
        </targets>
    
        <rules>
            <!--All logs, including from Microsoft-->
            <logger name="*" minlevel="Trace" writeTo="allfile" />
    
            <!--Skip Microsoft logs - no writeTo attribute-->
            <logger name="Microsoft.*" minlevel="Trace" final="true" />
            <logger name="*" minlevel="Trace" writeTo="ownFile" />
        </rules>
    </nlog>
    

    Publish nlog.config

    Make sure that the nlog.config will be published, e.g in your csproj file:

    <ItemGroup>
        <Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
    </ItemGroup>
    

    Output

    "nlog-own-2018-02-14.log" contains:

    2018-02-14 16:27:04.0547|aspnetCoreApplication.Controllers|INFO|created homeController

    2018-02-14 16:27:04.0547|aspnetCoreApplication.Controllers|INFO|created homeController

    Troubleshoot

    Missing debug log messages in ASP.NET Core 2? While the we use SetMinimumLevel in program.cs, also appsettings.json could confluence this.

    You could change that as follows:

    Change appsettings.json:

    {
        "Logging": {
            "LogLevel": {
                "Default": "Trace"
            }
        }
    }
    

    You could also filter Microsoft's logs here, e.g.

    {
        "Logging": {
            "LogLevel": {
                "Default": "Trace",
                "Microsoft": "Information"
            }
        }
    }
    

    Other issues, see this step plan to find the cause: Logging-troubleshooting in NLog

    Cheers,

    Julian (NLog)

    Edit: updated for NLog.Web.AspNetCore 4.3

    Edit 2: Updated for ASP.NET Core 2 and latest recommendations

    Edit 3: Updated for ASP.NET Core 3

    0 讨论(0)
  • also usable for .net core console application.

    private static void ConfigureNlogConfig(string configFile){
      LogManager.Configuration = new XmlLoggingConfiguration(Path.Combine(Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath,configFile), true);
    }
    
    0 讨论(0)
  • 2020-12-02 16:25

    There are now official Wiki-pages for how to use NLog with ASP.NET Core:

    NLog Wiki - Getting started with ASP.NET Core 3

    NLog Wiki - Getting started with ASP.NET Core 2

    NLog Wiki - Getting started with ASP.NET Core 1

    0 讨论(0)
提交回复
热议问题