Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Logging to file in asp.net core using nlog

Suggested Videos
Part 60 - Global exception handling in asp.net core mvc | Text | Slides
Part 61 - Logging in ASP.NET Core | Text | Slides
Part 62 - Logging exceptions in ASP.NET Core | Text | Slides

In this video we will discuss how to log to a file in ASP.NET Core using NLog.

ASP.NET Core supports several third-party logging providers like the following
  • NLog
  • Serilog
  • elmah
  • Sentry
  • JSNLog

If we know how to work with one of the third-party logging providers, working with the other's is similar.

Using NLog in ASP.NET Core

Step 1 : Install NLog.Web.AspNetCore nuget package

Once the NLog package is installed, you will see the PackageReference included in the .csproj file

<PackageReference Include="NLog.Web.AspNetCore" Version="4.8.2" />


Step 2 : Create nlog.config file

Create nlog.config file in the root of your project. I have included the minimum configuration required.

<?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">

  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file  -->
    <target name="allfile" xsi:type="File"
            fileName="c:\DemoLogs\nlog-all-${shortdate}.log"/>
  </targets>

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

To learn more about the nlog.config file please refer to the following github wiki page
https://github.com/NLog/NLog/wiki/Configuration-file

Step 3 : Enable copy to bin folder

Right click on nlog.config file in the Solution Explorer and select Properties. In the Properties window set 

Copy to Output Directory = Copy if newer

Step 4 : Enable NLog as one of the Logging Provider

In addition to using the default logging providers (i.e Console, Debug & EventSource), we also added NLog using the extension method AddNLog(). This method is in NLog.Extensions.Logging namespace.

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
            logging.AddDebug();
            logging.AddEventSourceLogger();
            // Enable NLog as one of the Logging Provider
            logging.AddNLog();
        })
        .UseStartup<Startup>();
}

If you want only NLog as the logging provider, clear all the logging providers and then add NLog.

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .ConfigureLogging((hostingContext, logging) =>
        {
            // Remove all the default logging providers
            logging.ClearProviders();
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            // Add NLog as the Logging Provider
            logging.AddNLog();
        })
       .UseStartup<Startup>();
}

Next video : Control what is logged using the LogLevel configuration setting.

asp.net core tutorial for beginners

4 comments:

  1. hello sir,
    While including below code in Program file,i am getting error as a "hostingContext does not exist in current context".Please guide me

    .ConfigureLogging((hostingContext, logging) =>
    {
    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
    logging.AddConsole();
    logging.AddDebug();
    logging.AddEventSourceLogger();
    // Enable NLog as one of the Logging Provider
    logging.AddNLog();
    })

    ReplyDelete
  2. Dear All,

    This is very good article for NLog kindly refer if you have any issue.

    ReplyDelete
  3. how to do 3rd step in visual studio code?

    ReplyDelete
  4. how to use in .net core 6?

    ReplyDelete

It would be great if you can help share these free resources