Ajinkya Gadgil
Ajinkya Gadgil

Reputation: 147

Nlog integration for logging in asp.net core API

I am planning to use nlog for logging purpose and I have added 'NLog.Web.AspNetCore' package into .net core 3.1 web API. Along with that I followed following steps:

  1. Installed 'NLog.Web.AspNetCore' package.
  2. Add nlog.config file
  3. Changed code in startup file
  4. Added declaration and DI in the controller
  5. Added the logger

Below is the blog.config file

<?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

  <!-- optional, add some variables
  https://github.com/nlog/NLog/wiki/Configuration-file#variables
  -->
  <variable name="myvar" value="myvalue"/>

  <!--
  See https://github.com/nlog/nlog/wiki/Configuration-file
  for information on customizing logging rules and outputs.
   -->
  <targets>
    <targets>
      <!-- write to file -->
      <target name="f" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log"
              layout="${longdate} - ${message} -   
        ${exception:format=StackTrace}${newline}" />
    </targets>
    <!--
    add your targets here
    See https://github.com/nlog/NLog/wiki/Targets for possible targets.
    See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
    -->

    <!--
    Write events to a file with the date in the filename.
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
    -->
  </targets>

  <rules>
    <!-- add your logging rules here -->

    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
        -->
    <logger name="*" minlevel="Trace" writeTo="f" />

  </rules>
</nlog>

program.cs file modifications

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                    .ConfigureLogging((hostingContext, logging) =>
                    {
                        logging.AddNLog(hostingContext.Configuration.GetSection("Logging"));
                        logging.AddConsole();
                        logging.AddDebug();
                        logging.AddEventSourceLogger();
                        logging.AddNLog();
                    });
                });
    }

Controller declarations and usage

  private readonly ILogger<PatientController> _logger;
        public PatientController(ILogger<PatientController> logger)
        {
            _logger = logger;
        }

            try
            {
                return Ok(await _patientHandler.GetPatientsInformation());
            }
            catch(Exception ex)
            {
                _logger.Log(LogLevel.Error, ex.Message, ex.StackTrace, null);
                return BadRequest("Some error occured while fetching the patients");
            }

But even after this my file is not getting generated. Am I missing anything here. Thank you

Upvotes: 1

Views: 5449

Answers (1)

Julian
Julian

Reputation: 36700

For ASP.NET Core 3.x you should use .UseNLog. Please note it's also not inside the ConfigureLogging method

for example:

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

See also Getting started with ASP.NET Core 3

If you still having problems, check the Logging Troubleshooting guide

A full working example could be found here

Upvotes: 3

Related Questions