Skip to content
ZhangYang edited this page Jul 7, 2019 · 3 revisions

Nlog was used in RestAiline for logging ASP.NET Core logging

Install the latest:

in csproj:

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

Create config file

Create nlog.config file in root of the api project:

Edit csproj:

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

Update program.cs

Write logs

Inject ILogger into your class:

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        _logger.LogInformation("Index page says hello");
        return View();
    }
}

Checkin logs

Checkin console and Logs folder in bin

Write unhandled exception in logs

Write a filte for intercept unhandled exceptions:

public class UnhandledExceptionFilter : IExceptionFilter
{
    private readonly ILogger<UnhandledExceptionFilter> _logger;

    public UnhandledExceptionFilter(ILogger<UnhandledExceptionFilter> logger)
    {
        _logger = logger;
    }

    public void OnException(ExceptionContext context)
    {
        _logger.LogCritical(context.Exception, "Unhandled exception");
    }
}

Add this filter in MVC configuration:

services.AddMvc(options =>
{
    options.Filters.Add<UnhandledExceptionFilter>();
});
Clone this wiki locally