aliemre
aliemre

Reputation: 129

NLog doesn't log in ASP.NET Core controller

I am trying to use NLog in my ASP.NET Core 3.1 app. I am trying to log my controller actions. Internal logs are created successfully. It means my nlog.config is read correctly.

I am injecting the logger into my controller and trying to log. But log file is not created. Tried so many things. Checked stackoverflow but couldn't find a solution.

If I put name "*" in my rule, it works, it creates log file named _logs.csv. But for my controller case it's not working.

Here is my nlog.config:

<?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="Trace"
      internalLogFile="c:\temp\internal-nlog.txt">

  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <targets>

    <target
      name="fileLogger"
      xsi:type="File"
      fileName="./_logs.csv" >

      <layout xsi:type="CsvLayout" delimiter="Tab" withHeader="false">
        <column name="Time" layout="${longdate}"></column>
        <column name="Level" layout="${level}"></column>
        <column name="Message" layout="${message}"></column>
        <column name="Error" layout="${exception:format=tostring}"></column>
        <column name="Route" layout="${aspnet-request-url}"></column>
        <column name="IP" layout="${aspnet-request-ip}"></column>
      </layout>
    </target>
  </targets>

  <rules>
    <logger name="FrontEndApplication.*" minlevel="Trace" writeTo="fileLogger"/>
  </rules>
</nlog>

My controller

[Route("api/testapi")]
public class TestApiController : Controller
{
    private readonly ILogger<TestApiController> logger;

    public TestApiController(ILogger<TestApiController> _logger)
    {
        this.logger = _logger;
    }

    [Route("postdata")]
    [HttpPost]
    public async Task<IActionResult> PostData([FromBody] TestModel data)
    {
        try
        {
            logger.LogTrace("Entered. Data is {data}", data);

            if (data.MultiOperation == null || data.MultiOperation.Value == false)
            {
                logger.LogTrace("Single operation.");
            }
            else
            {
                logger.LogTrace("Multi operation.");

                for (int i = 0; i < 5; i++)
                {
                }
            }

            return StatusCode(200, apiResult);
        }
        catch (Exception err)
        {
            return StatusCode(500, err.Message);
        }
    }
}

My program class

public class Program
{
    public static void Main(string[] args)
    {
        try
        {
            NLogBuilder.ConfigureNLog("nlog.config");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception err)
        {
            throw err;
        }
        finally
        {
            NLog.LogManager.Shutdown();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        }).UseNLog();
}

And my appconfig

  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Trace",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }

Upvotes: 2

Views: 2628

Answers (1)

aliemre
aliemre

Reputation: 129

It was the Logging property in appsettings.json. I added my application's namespace to log levels and it started working.

 "Logging": {
    "LogLevel": {
      ...
      ...
      "FrontEndApplication.*": "Trace"
    }
  }

See also: https://github.com/NLog/NLog.Web/wiki/Missing-trace%5Cdebug-logs-in-ASP.NET-Core-3%3F

Upvotes: 5

Related Questions